You are on page 1of 299

w. Kinzel/G.

Reents


Ie
b~
ut
Programming Physical Problems
Using Mathematica and C
W
..

Springer
Using Mathematica and C

Translated b Martin CIaus and Bever! Freeland-Claus

With 88 Figures) 33 Exercises and a CD-ROM


Containing Programs and Graphics Routines for PCs
)
. ~ .
Prof. Dr. Wolfgang Kinzel Dr. Martin Clajus
..... r-. r-." .... r-..... 1 ~ 1 .~..
r l tV.-UU:.G. UI. Ut:UI ~ ... Uf. ve; ve;lj' ~, -....,.vi.]US
Institut fUr Theoretische physik Deot. of Physics & Astronomv
UniversiUit Wiirzburg UCLA
Am Hubland Box 951547
D-97074 Wiirzburg Los Angeles, CA 90095-1547, USA
e-maIl: e-maIl:
kinzel@physik.um-wuerzburg.de c1a}us@physics.ucla.edu
reents@physik.uni-wuerzburg.de

The cover picture shows a space-time diagram of the probability of presence of a quan-
tum particle in a square-well potential.

This American edition has been revised bv the authors. The book was oriQ:inallv oublished
in German: W. Kinzel, G. Reents: Physik per Computer, Spektrum Akademischer Verlag,
Heidelberg 1996

CIP data applied for


Die Deutsche Bibliothek - CIP-Einheitsaufnahme
Physics by computer: programming physical problems using Mathematica and C; with 33 exercises and a CD-ROM
containing programs and graphics routines for PCs and workstations; Mathematica 3.0 compatible I Wolfgang
Kinzel; Georg Reents. Trans\. by Martin Clajus and Beverly Freeland-Clajus. - Berlin; Heidelberg; New York;
Barcelona; Budapest; Hong Kong; London; Milan; Paris; Santa Clara; Singapore; Tokyo: Springer.
Einheitssacht.: Physik per Computer <engl.>
rCD'" v

This work is subject to copyright. All rights are reserved, whether the whole or part of the material is concerned,
specifically the rights of translation, reprinting. reuse of illustrations, recitation, broadcasting, reproduction on
microfilm or in any other way, and storage in data banks. Duplication of this publication or parts thereof is
permitted only under the provisions of the German Copyright Law of September 9, 1965, in its current version, and
(nr .. N' ...... d ;".,,,,,. ]"A frnrn . \7 ...1. . "rA \;"],,!A fnr ..n,JAP .hA

Springer-Verlag Berlin Heidelberg 1998


Printed in Germany
Mathematica is a rel!istered trademark bv Wolfram Research, Inc.

ine .~se 01 ge~eral


u .., v,
.,...,
1-'............
name~:.
, ,
. names.
u 1-"
r
HV'"
,en;. In mls.
,....
.
. uoes nor implY' even
.............
. in
v

and therefore free for general use.


Please note: Before using the programs in this book, please consult the technical manuals provided by the
manufacturer of the computer, and of any plug-in boards, to be used.The authors and the publisher accept no legal
. .. . .. ..
:espUnSllJ~~lY lUI any ~aust:u lJy : ust: UI lilt: .1:. 'UI~ v llt:rt:I~:;
'" ... ~ .. ~ . . '" ~,,~ v~~ .. ,~~.~~ ..... ~~.~. ,~~~ .. v . . ~. "V . v. . . . ~. ...~ . . . ~l ....
function correctly. The programs on the enclosed CD-ROM are under copyright protection and may not be
reproduced without written permission by Springer-Verlag. One copy of the programs may be made as a back-up.
but all further copies offend copyright law.
~Uver uesigll: I\.UIll<.el LUpl<.il,

c
Preface

For some apparently simple physical models there are only numerical answers
so far. We know universal laws that any high school student can reproduce on
? .

works, combinatorial optimization, biological evolution, formation of fractal


structures, and self-organized criticality are just some of the topics from the

This book evolved out of lectures at the University of Wiirzburg, Ger-


many, for physics majors after their fourth semester - those having completed
the introductor c r w i
VI Preface
..
"

1""".1 OJ.'-'O r
" ... ,
~ ~
oVJ.J.J.'-' v...
." ..1. ~ ,~ ~~ ~I. ~
'H J.J.J.'-'J.J. ....... '-' .... u UJ.J.'-'
..1
uo '-'~o'-' v ...
~ ,
..1 ~
u.J.J.~ UJ. J.~O

to SOlve tnem wltn SImple aJgoritnms.


One goal is to encourage our readers to do their own programming. Al-
though a CD-ROM with finished programs is enclosed with the book, they are
. .
not meant as user-rnenOlY experimental environments. --~
A

we .nope tnat insteaa


'

they can be taken as a starting-point, and we encourage our readers to mod-


ify them, or better yet to rewrite them more efficiently. Exercises accompany
every section of this introductory book.
We have received suggestions from many colleagues and students, to whom
n11l" th~n1rc:! Wo ll1ro 11 tn 1\11" Rlohl
UTO UTlc:!h tn
.. "C .,
H. Dietz, A. Engel, A. Freking, Th. Hahn, W. Hanke, G. Hildebrand, A. Jung,
A. Karch, U. Krey, B. Lopez, J. Nestler, M. Opper, M. Schreckenberg, and
n n
1
n-

. .1.1.
1
Con"",..; ..1 th:lnk~ uo to t.hp.
. .... V,
11
. ,.
..
.... "..,. .. . ..
........
.1.
T
.:L
10"" I.
.

r. . . .

...
.
~~
""'.~
'C .... . C.... ~"'9'
1\ If.
'C
, J.'.La... IIJ.J.J. UJ.J.~

on Unix, and Ursula Eitelwein typed the manuscript of this book in UTEX.
Finally we would like to thank Martin Clajus for valuable suggestions in the
. .. .1.1. ., .. . T':' ...... .
v .. ""
.... IIJ.J... O J.J.""V ....
TTT.

'0
TrT
' . J~ .

'" 07
'07
'V.:... _~l
..... U 'UN,",U

July, 1997 Georg Reents


Contents

or .. . .................................................. ..
~

1. Functions In Mathematica
. ............................... 3
1 1 . ..,. . ~- 'I
. .............................. A
,. ,.
4
L~
.... .-n1
~lle
.... T
1...
T"Io
.I.
1 1
............................... u
1.3 Fourier Transformations ................................. 13
1.4 Smoothing of Data ..................................... 20
4 ,.
.. ...... .......................................... nn
.... T
LtJ .1' .I'lL ~tJ

1.6 Multlpole ~xpanslOn .................................... 3U


1.7 Line Integrals .......................................... 36
1.8 Maxwell Construction ................................... 38
1.9 The Best Game Strategy ............................... 42

2. Linear Equations . ........................................ 47


2.1 The Quantum Oscillator ............................... 47
2.2 Electrical Circuits ...................................... 52
?~ nh::lln vp !iQ
,..
n
"'."'1:
AI mI.
.I. .l.l'V
TT r. 'I T"Io
............................... v..,
.,
.V
~~

2.5 The Hubbard Model .................................... 71


3 Tt . ~1
~ .
.., .1.
~.
.I.
.I .
. ...................................
T"
JJ)
n ..
O~
&

3.2 The Frenkel-Kontorova Model ........................... 93


3.3 Fractal Lattices ........................................ 101
~ AI 1\.T. _I 1\.T 1 .. n~
"'."'1: .1 ~~6~& .1 ~v ~&&.~ ..L.UV

4. Dilterentlal Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 115


4.1 The Runge-Kutta Method ............................... 115
4.2 The Chaotic Pendulum .................................. 121
4.;1 ~tatlonary ~tates ....................................... IJU
4.4 Solitons ............................................... 136
4.5 Time-dependent Schrodinger Equation .................... 144
VIII Contents
I!' 1\/L ~ n .1 C". _'I .L.
1~'"
u. .LV,

a.1 ltanaom 1'1 umoers . ..................................... Ial


5.2 Fractal Aggregates ...................................... 163
5.3 Percolation ............................................ 171
~.

,')Ji rOlymer vllaInS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101


5.5 The Ising Ferromagnet .................................. 190
5.6 The Traveling Salesman Problem .......................... 200

A.
-. .:neps wun
.rlrs't
~ . . --a.,;nemanca
..
lY.l . . . . . . . . . . . . . . . . . . . . .t;ll

B. First Steps with C . ....................................... 225


c. First Steps with Unix ..................................... 235

u. FIrst ~teps wIth Xgraph'tc8 . ............................... 245

E. Program Listings ......................................... 249


Inaex ......................................................... ~~;j
Introduction

gram which is supposed to solve the problems from the first part is described.
Only the essential commands are explained so that the readers can try to com-

x
codes are available on the enclosed CD-ROM. In the results part, some re-
sults of the computer calculations are illustrated, for the most part in the

for each problem. The choice of these citations is, of course, subjective and
no claim of completeness is made. At the end of every section, there is an
exerCIse.

over e ements 0 ,IS 0 ten use or -intensive computer simu ations.


MAPLE is also a very popular tool for computer algebra. All of our pro-
grams run not only on fast workstations, but also on a PC operating under
or mux.
2 Introduction

to be defined, and the contents of the display memory have to be written to


the monitor. To do so, one has to learn complicated new languages like XII,

generate on, hopefully, any workstation monitor elementary graphics with


relatively few commands. This package is included on the enclosed CD-ROM.

server an compI e I. ersions 0


package are included as well.
All C programs in this book are described in the PC version. However,
the figures were produced with Xgraphics. For the most part we have shown
the windows as the a ear on the monitor.
Most C programs can be controlled interactively during their execution.
The versions for the PC as well as those for the workstation allow the user
to chan e some arameters or al orithms or end the am via ke board

We want to emphasize again that our hardware and software equipment


are by no means necessary for working through the physics problems. Every

1. Functions In M athematica

...
nil
.
II.l.le
- .
.................. u .lUC.l
_ . ,.
.lCVC.l U.l p.l
..
.
......
I'
...... ...... , CL.l.l'y
o. .
processes small packets ot on-ott data t bits) step by step. ~very packet gives
instructions to electronic switches that cause the results of elementary math-
ematical operations to be written to memory and new data to be read. This
level ot processIng elementary InstructIOns step oy step, nowever, IS narmy
suited to the formulation of more involved problems by humans.
This is why complex algorithms should be structured. Correspondingly,
high-level programming languages consist of functions or modules. In order to
keen a nrOQTam comnrehensible one should use modules that are orQ"anized
~-~~
.... "'...... ...... +~ .c~~ A ~ ~ _ 1~ ~ _~~..:J
u'" ................ A..., ................., .... 0"''''..... .....
~4-9.1~ 99.:11
...... "'UJ""'" ." .........................
C
~ 14-:~1~
..
..
levels of modules; this has the advantage of simplifying the modification of
such programs by making it more likely that only individual functions will
l. n
...... 4-,..
....""..." J.,."
u..............
_L -l

. .
. . .large . .
.- .
lV1 a~nemanca
. ....... UI
IS a programmIng language
. lug a

functions that are easily called, however, since most parameters have default
values and do not necessarily have to be specified. Indeed, every command in
..... ,., , ,.
t;au
. . ,
U~ .l COCL.l u c u
. CL1:l CL
"
LUCLL I:)
. .. .y CLUU

is relevant for all subsequent and sometimes even for previous commands.
In this sense, Mathematica is located right at the top of the hierarchy of
programming languages.
By comparison, C, Fortran, Pascal, and Basic, although they, too, are
,-' .'- 1 rr
'~~1 and . '- . .1 1' .
...... ..
I ,~
...... ...... ......
~ -~~
...... ...... ...... ..
(after all, Mathematica is written in C), require much more effort than Math-
ematica in order to, say, generate a graph of a Bessel function in the complex
..nlane. ,
'T'1-.:~ ~1-.~~4-~
............, C ....,
:~. -l -l 4-~
u'"
4-1-. ~ -l 4-~ 4-1-.~ .. ~~ ~~
u........ .. ................... u'" u........ ........... "'..
"Af J.J..~
....~ ...,Vl""",

matica. vvitn simple examples, tne IOl1owing applications are aemonstratea:


elliptic integrals, series expansion, Fourier transformation, X2 distributions,
3D graphics, multiplication and integration of vectors, determining the zeros
.. , . Cl..
Ul
. ..
, aIla ...
. .Za1JIUIl.
4 1. Functions in M athematica

In order to illustrate the difference between processing commands step by


step, a method for which we want to use the term "procedure", and call-
mg a pre e ne unc ion, we wi use a simp e examp e: e m an v ue 0
10000 random numbers, distributed uniformly in the interval [0,1], is to be
determined. In Mathematica, the data are generated as follows:

In order to determine the mean value, we have to add up all these numbers
and divide the sum by the number of values. We can program this step by

Do[sum = sum + data[[i]], {i,length}];


average = sum/length ]

In this case we use functions that take advantage of the structure of Mathe-
matica. The argument data is entered as a list of numbers. Apply replaces the

Note that average appears three times: as a local variable and as the
name of two functions, one of which has two arguments, the other just one.

case.
The reader will find an introduction to Mathematica in Appendix A; nev-
ertheless, we want to point out some features of this language here: the un-
derscore character in the argument data_ indicates that it can be replaced

: = reevaluates the right-hand side each time the function is called, whereas
= evaluates it only once. For example, r : - Random [] will result in a new
1.1 Function versus Procedure 5

We increase the number of array elements to be averaged from 10000 to one


million so that we obtain run times of the order of seconds:
#include <stdlib.h>
#include <time.h>

#define LIMIT 1000000

double average(double *,long), dataset[LIMIT];


clock_t start,end;
long i;

start=clock 0 ;
printf(" average = y'f\n",average(dataset,LIMIT;
end=clock 0 ;

double average( double *data,long n )


{
double sum=O. ;
ong 1.;
for i=O;i<n;i++ sum=sum+data i
return sum/n;
}

vantages. For example, what is transferred to the function average is the


memory location of the array dataset; more precisely, dataset is a pointer

double *data means that data contains the address of a variable of type
double. Warning: dataset [1000000] is some undefined entity; referencing
it will not cause the computer to report an error but will usually produce
comp ete y mcom re enSl e resu ts.
Unfortunately, a comma, semicolon, and various kinds of parentheses have
completely different meanings in C and Mathematica. But why should life be
easy for computer users?

a value close to 0.5 after about ten seconds. By comparison, the version
6 1. Functions in M athematica

Literature

, ,
Wolfram S. (1996) The Mathematica Book, 3rd ed. Wolfram Media, Cham-
paign, IL, and Cambridge University Press, Cambridge

The mathematical pendulum is a standard example in any physics course on

Physics

massless, rigid string of length l swings in the earth's gravitational field. Let
Ip(t) be the angle of displacement from the pendulum's equilibrium position
I

E = ; l2 <jJ2 - mgl cos<p = -mgl cOSlpo , (1.1)


where Ipo denotes the maximum displacement angle with CPo = 0, and <jJ =
t is t e an u ar velocit. om this e uation one can obtain t b
using a little trick: one separates t and Ip by solving (1.1) first for (dlp/dt)2
and then for the differential dt. For the half period in which Ip increases with
t one obtains
1.2 The Nonlinear Pendulum 7

t 1.3
cos <P - cos <Po

Obviously, the period T is four times the time the pendulum needs to reach
its maximum angle <Po:

Since the integrand of (1.3) diverges as <p' -+ <Po, it makes sense to use the
substitution

1.
<Po
which results in the following integral:

t
1 - sin 2 (<Po /2) sin2 "p'

T=4 1.7

we look at the phase-space diagram ep versus <P for various energies E. The
generation of higher harmonics with increasing nonlinearity is visualized by a

Algorithm

by the commands
8 1. Functions in M athematica

and
EIIipticF[psi. k-2]

various conventions for using them. Thus, we have K(k) =EllipticK[k-2]


and correspondingly for the other elliptic integrals. According to (1.7), the
. . l'l'yu"\lu
. .
T[ hiO_] =4 EIIi ticK[Sin[ hiO/2]-2]

where we have set Jf79 = 1. The command Plot draws the period as a
function of CPo:
-)

phinorm[x_.phiO_]:=
2 ArcSin[Sin[phiO/2] sinepsi[x T[phiO]. phiO]]/phiO

flist = TabIe[phinorm[x.phiO[i]].{i.5}]
We can now draw this list using Plot, after first applyin the command

In order to study the generation of higher harmonics with increasing non-


linearity CPo, we expand cp(t) into a Fourier series. This is most easily ac-
lish in h il _.
1.2 The Nonlineax Pendulum 9
.#.
~
."1': _ ... _
.. _- ...
Al..._ r r _ _.: __ r"1': _ ... "
..-- .... '

If, in (1.1), the energy E is kept constant, one obtains curves in the (<i;, cp)
plane, the so-called phase space. Plotting these curves is surprisingly simple
in II lL
.- r~l1infJ" r
hv "', 01: for t.hp .
.... R(ln
, .
II)) 1'hp
.
,.,
'"'v.u. ... vu..Li:> .... 1.J;o.L,
r ..... ... ....
J;o~, ,
~

"".. "1
~J ~a.u
1-
tJv UOVU
.J
lIV
1-
ua.vv 'IJ
0
.1
.L-
.-'1 .
"'V.L

various values of E.
Finally, a remark concerning the series expansion of T(cpo). The new ver-
. (q {\\ . II lL _11"_ ~,,_ _ l' "P_ l__ _.f (1 7\ hn
"'.LV.L.L \ V.V J V.L "'~.L .... ~'-J -..- ....~. \~~
I "'J.
usmg tne commana ::ier1eS, wnereas Olaer versIOns Wlll OUtpUt omy IOrmal
derivatives of of EllipticK.
A possible way to handle this problem is to start with the integral (1.6)
for 'ljJ = 7r /2. The integrand is
p p .~ .~
:r - .11 ;:>qrl;; L.1 - m ;:>~n LpS~J ~J

with m = sin 2 (cpo/2). f can be expanded in terms ofm, e.g., up to 10th order
in m 1 ()
,

- = Series
fT rf {m 0 lO}l

Then, every single term can be integrated over 'ljJ by using Integrate. Finally,
the value sin 2 (cpo/2) is substituted back for mvia /. m -> Sin [phiO/2] "'2.

Results
.
Wp h::t.vp
1- . ~,,-
_1 t.hp
.. '
rr of t.hp
. ,,- .J ~1
l' .1 {I)n

T.'~
. ~
1

...
_1

... .1-
i~::t.
.1-
of t.hp
.J fJ'1
.J.lIJ, VJ.J. lIJ.J.V VI. lIUv ..- .I: J.5Ul.V .............. ~ .... 1IJ.J.'-' ..- .L

as a tunctlon ot tne amplltuoe CPo. It takes tne penOUlum an mfimte amount


of time to come to rest at the highest apex (CPo = 7r). We can see that at first,
with increasing CPo, T does not deviate greatly from the value for the harmonic
. ~
-
penaumm,.1 - ~7r. vmy lOr amplltUaeS aoove ~u - 7r I ~ IS.1 slgmnCantlY
larger. The influence of CPo on the curve cp(t) is evident in Fig. 1.2, where
the ratio cp/CPo is plotted as a function of tIT in order to compare different

."'.....
IVI I

8Pi

6Pi J
T /

~
4Pi

2Pi

()
0 Pi/4 Pi/2 3Pil4 Pi
~lg. Tne penOd 1. as a tunc-
L 1.
phiO tion of the amplitude <po
10 1. Functions in Mathematica

0.5

Fig. 1.2. Normalized dis-


-0.5 placement lpnorm (t /T) of

o 0.2 0.4 0.6 0.8 71",71",


and 99971"/1000
tff inside out)

s s"
because of the periodicity ep(t) = ep(t + T), the frequencies W s are integer
multiples of 21f IT. The discrete Fourier transformation available in Mathe-

(s-1)(r-l)
21fl

6
....,
.......
~4
......
'"
< 2

0

2 4 6 8 10 12 14
1.2 The Nonlinear Pendulum 11

such phase-space curves for different energies E. For small CPo, one obtains
a circle that becomes deformed as the energy increases. For E > m 9 l, the

produces the following somewhat unwieldy output on the monitor:

2 Pi + ------------- + --------------- + ---------------- +


2 32 128

2 2 2
> ------------------ + ------------------- + -------------------- +
8192 32768 524288

P 1 P 1
184041 Pi Sin[----] 41409225 Pi Sin[----]
2 2
> --------------------- + ----------------------- +

phiO 18 phiO 20
147744025 Pi Sin[----] 2133423721 Pi Sin[----]
2 2

-3
-Pi -Pi/2 o Pil2 Pi
phi
12 1. Functions in Mathematica

> O[Sin[----] ]
2

2 32 128 8192

39691rsin lO !EQ.
2
533611rsin12 !EQ.
2
1840411rsin14 !EQ.
2
+ ----3-2-76-8---=-+ 524288 + 2097152

414092251rsin 16 ~ 1477440251rsin18 ~
+ ----5-3-68-7-0-91-2----'''- + 2147483648

21 11
+

than 1200 ; beyond that, it increases significantly.

ExerCIses

1. Calculate the period T as a function of 'Po, once using EllipticK and


then with Nlntegrate. Compare the processing times and the precision
of the results.

of the amplitude 'Po (-- increasing nonlinearity)? Calculate the Fourier


coefficients Ib s l/lb2 1 as functions of 'Po.
. .

Start: bo = COSct,
Iteration: bi+l = Vaibi ,
Sto :
- 2an '

xamp es
from Classical Mechanics to Fractals. TELOS, Santa Clara, CA
1.3 Fourier Transformations 13

,
Zimmerman R.L., Olness F.I., Wolpert D. (1995) Mathematica for Physics.
Addison-Wesley, Reading, MA

1.3 Fourier Transformations

his or her disposal: the decomposition of the signal into a sum of harmonic
oscillations. This tool, which has been thoroughly investigated mathemati-

most any signal, even a discontinuous one, can be represented as the limit of
a sum of continuous oscillations. An important application of Fourier trans-

unc Ion III erms 0 simp e OSCI a Ions pays a Ig ro e no on y III P ySICS,
but also in image processing, signal transmission, electronics, and many other
areas.
Frequently, data are only available at discrete points in time or space.
In this case the numerical al orithms for the Fourier transformation are
particularly fast. Because of this advantage, we want to investigate the Fourier
transformation of discrete data here. In the following sections we will use it to
smooth data to calculate electrical circuits and to anal ze lattice vibrations.

Mathematics

Let ar , r = 1, ... , N be a sequence of complex numbers. Its Fourier transform


IS e sequence s, 8 = , ... ,

(1.8)

N
_ 1 '" b . (r - 1) (8 - 1)
ar - -- L..J s exp - 21I"1-'-----'----'---~ (1.9)
s=1
Thus, the signal {ai, ... , aN } has been decomposed into a sum of oscillations
bs
c r =--

s- s- s s
of an amplitude and a phase. Both (1.8) and (1.9) can be extended to all
14 1. Functions in Mathematica

perlo
(1.11)

symmetry:

1 ~ . (r - 1) (-8 + 2 - 1)
= - - LJ a r exp 27fl N

(1.12)

A useful property of Fourier transforms becomes evident in the convo-


lution of two sequences {/r} and {gr}. In this operation, the elements Ir
. . . .

Let the sequences {h s }, {gs}, and {fs} be the corresponding Fourier trans-
forms. Combining the Fourier expansions

. (m - 1) (j - 1)
N
1 N_ . (n - 1) (r - j)
Ir+l-j = N Lin exp - 27fl....:.....---:.....-'------.;....;...
N
1.3 Fourier Transformations 15
I 1 '\ 3
h. - I --.::..- \ '\' n. .I.
L...J
\yN} r,j,m,n "

. (r - 1) (s - 1) - (m - 1) (j - 1) - (n - 1) (r - j)
xexp 2~1 AT
.1.1'
.
The sums over rand j can be evaluated

~
L.J
Avn
-r
(?'7I"l
\
lq.) - 1\T Ji
. .,,""
. ... , lo t=. '71.
t:....:l
NJ

and we are left with

hs = VN L iJmin exp (2~i


, m. ~) 8s- n,o 8n- m ,o = VNiJsis . 1\T (1.14)
m,n /

Thus, after the transformation, the convolution turns into a simple product.
The inverse transformation then yields the convoluted function

hr
l:!...
) fl.'l Is exp 2~i
(".
'
l'-, , (r: n
"

. (1.15)
~
lV
s=l
In the next section, we will use the convolution to smooth experimental data.

Algorithm

In Mathematica, one obtains a list of the Fourier coefficients {b1 , .. , bN}


via tne cornmana
"'our~er l tal, .. , al'UJ

and their inverse by using


InverseFourier[{bl, ... , bN}]

It may be interesting anyway to look into the Fast Fourier 'I'ransform (FFT)
algorithm. The most straightforward way of calculating all series elements bs
accoraing to ~ l.lS J amounts to mUltlplymg a matrIX OJ tne IOrm
, , .
IN ~ ~,

2 . ~1' .1) ~ ~ .1)


Ws,r (N) = exp ~l
N
bv a vector a - (a, .. aJ\T) this takes N2 stens. The FFT allrorithm how-
"''O.'''........... ~ .1 ,1. +l.", ............. '" ;~ .... ..,......... l."'... ,..~ "'+"'Y"'" +h .... + .1 __ ~~
'V 'V~, 'V..-&
&
U&&'V .... ..-~&'V &&~ .... ""~ .... u ' V , t ' .... U&&.... u --- _ - -- .1 .....,
...,......

N log N. To this end, the sum (1.8) is split up into two partial sums with
odd and even indices r:
16 1. Functions in Mathematica

t=l t=l

+exp

1
V2
Here, b~(N/2) and b:(N/2) are the Fourier transforms of the coefficients

F(N)=2F(~)+kN. (1.17)

Application

J(t) = ~ [sign (r + t) + sign (r - t)] (1.18)


1.3 Fourie:r; Transformations 17

n=-oo

where w = 271" IT and the In are determined by integrals over f(t)


T/2

f (t) exp (-inwt) dt . (1.20)

this inte ral is easil executed the result is

(1.21)

00
bs
v'N -
_ [.
exp 1 71"
(N - 2) (s - 1)]
N L
k=-oo
fI-s+kN. (1.22)

00

L fI-s+kN (1.23)
k=-oo

n ' s - " ... , .


The question whether Ibsl/v'N < Ill-si or Ibsl/v'N > Iit-sl, the effect of
the so-called al~asing, cannot be a~swered in general. This depends on the

frequencies corresponding to N/2 < s < N. In (1.11) in the mathematics


18 1. Functions in Mathematica
0.2 .,
,
0.15 \

\
0.1

\ \/ \ ~ --
0'-- .......... v --...VV~
....... ........_ _--'-----'
5 10 15 20 25 30

Fig. 1.5. Continuous and discrete Fourier transformations of a rectangular pulse.


The solid curve shows 111-8 I as a function of s, the filled circles are the values of
Ibs IN- 1 / 2
1.25
1
I I
. IV .V

0.8
0.75
0.6
0.5
0.25 0.4

0 0.2
-0.25 0 .... AA IAAA
V"
-0.5
.
- -~ v ~ .. ..
- -~ v ~ ..
. ro.f 4-l. .... "
AO _._. - J~~ ._-- ~ \ ~J-' - - ~ \ 0;"00' -- ---
inverse Fourier transformation to continuous t values

. ..
part aoove, we nave snown tnat tne sum can oe taKen over any InterVal or
. .
length N. We take advantage of this freedom to choose an interval that is
symmetric to the origin and use only the lowest frequencies:
N/2
~ t. \ 1 ~ I. '" ~r - 1) ~S - 1)
J \"rj
V'" s=-N/2+1

1 N/2
. (r - 1) (s - 1)
= r:-; ~ bs exp - 21rI 1\1
.l.Y
V lV s-I

1 ~ b [ 2 . (r - 1) (Sf - N /2 - 1)]
+ ..;N LJ s'-N/2 exp - 11"1 N
s'-1
I\T J?

1 ~ . r-1)(s-l)
..;N ~ Ds exp . ~1I"1
N
1.3 Fourier Transformations 19

*N/2-s'+2

1. Peak voltage. A time-dependent voltage is probed at N = 64 points


in time resulting in the values U1 , , UN. Assume that its Fourier

random 'Ps. What does the signal look like now?


(c) Competition: The objective is to find phases that result in the
low st ssi I Ii..
{cp.. } r
2. Aperiodic crystal. Assume a chain of atoms with a periodic arrange-
ment.

ficients Ibsl of the function a r that is defined as


1 if atom 1 is at the position r ,
ot erWlse.
(a) Plot the Fourier spectrum bs .
(b) Next, generate a random sequence of Is and Os and plot its Fourier

(i) Start with: 0

(ii) Generate the next line by appending the next-to-Iast line to the
last one.
20 1. Functions in M athematica

Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Red-


wood City, CA

Press, Cambridge, New York


DeVries P.L. (1994) A First Course in Computational Physics. Wiley, New

am-

Experimental data are usually affected by a noticeable statistical error. The

YSICS

Let f(t) be a physical quantity that is measured at discrete times ti. The

9i = Ii + Ti , i = 1,2,3, ... , N . (1.24)

into account the neighbors according to their distance Ii - i I from the point
i. Very distant neighbors are only weighted weakly. As a weight function, or
1.4 Smoothing of Data 21

j=1

Then 9r is constructed as follows:


N

9r = L9r-j+1 k j . (1.26)
j=1

N
.(8 - 1) (r - 1)
N

where 9 and k are the Fourier transforms of 9 and k respectively.

We generate the data we want to smooth as an array data in Mathematica,


using the values of the Bessel function J 1 (x), and add noise in the form of

data=
Table[N[BesselJ[l,x] + 0.2 (Random[]-1/2)], {x, 0, 10, 10/255}]

u:

This, however, puts the largest functional values in the middle of the array

the command
kernel = RotateLeft[kernel,127]

kernel = kernel/Apply[Plus, kernel]

Sqrt[256] InverseFourier[Fourier[data] Fourier[kernel]]


22 1. Functions in M athematica

Figure 1.7 shows the results of the calculations done with u = 0.4. The
smoothed data are compared to the noisy data and to the original function.

curve" is used for the kernel. In the third edition these mistakes have been
corrected. Finally, we want to point out that one has to be careful when doing
. . . .. .

mials through adjacent interpolation nodes and require their curvatures to


be minimal. We cannot treat this broad area of statistical data analysis here;
1.5 Nonlinear Fit 23

The result of the algorithm for smoothing data introduced above depends on
the width u chosen for the kernel. Calculate the smoothed data for a wide

Press W.H., Teukolsky S.A., Vetterling W.T., Flannery B.P. (1992) Numer-

, ,
Wolfram S. (1996) The Mathematica Book, 3rd ed. Wolfram Media, Cham-
paign, IL, and Cambridge University Press, Cambridge

1.5 Nonlinear Fit

,
frequently fitted to the data. The models are - hopefully - the results of
theories; the computer is needed to find the "best" parameter values and

,
be able to specify a measure for the precision of the parameters.
Using the example of a damped oscillation that is measured at just eleven

Theor

z, z , , z
unknown M -component parameter vector a is to be fitted. Assume further
24 1. Functions in M athematica

vams w en average over many expenmen s an ave e vanances ui' I.e.,


(ci) = 0 and (cn = u;. a
The "best" set of parameters is defined to be the
vector ao whose components minimize the quadratic deviation X2 , where X2
IS e ne as 0 ows:

(1.28)

2
o

P N
-
M
(X~) = r () / o
N-M
e- t t-2-- 1
dt. (1.29)

,
the possibility that our experiment belongs to those 1% of all cases for which
X2 is greater than or equal to X5. If, however, we had P = 0.9999, our fit

x2 (a)has a minimum for some parameters ao and the value of x2 (ao) falls
within our confidence interval. If we could repeat the experiment several

wan
1.5 Nonlinear Fit 25

aI, a2, ... . From the width of the distribution of each component of the ak
we obtain the error bars for the fit parameters ao.

,
it can be shown that the quantity L1 = X2 (a)
- X2 (ao)
is again distributed
according to the distribution function P from (1.29), this time with M rather

(1.30)
determines the re ion of allowed values of a. In arameter s ace the re ions
of constant L1 are ellipsoids. The projection of this (M - I)-dimensional sur-
face onto the axis i then yields the error interval for the parameter ai.

For the nonlinear fit, too, it is easiest to use the functions available in Mathe-
matica. To find the minimum of x2 (a), we use the function NonlinearRegress
rom t e pac e Statistics'NonlinearFit'. t 0 ers vanous POSS1 Illes
for entering data and initial conditions; in addition, one can change the
method of the minimum search and have the program display intermedi-
ate results. Of course, one can also provide one's own definition of x2 (a) and

oscillation
f[t_] := a Sin[om t + phi] Exp[-b t]

with four parameters a = {a, om, phi, b}. This oscillation is measured at
11 points in time ti for the parameter set a = {1, 1 ,0,0. 1}, and noise in the
form of uniformly distributed random numbers is added to the data:

om ,
{t, 0, 3Pi, 0.3Pi}]
26 1. Functions in Mathematica

0.2

/ x
2
dx
2
= 150 .

e searc or a mInImUm IS aClltate 1 we can provi e an approximate set


of values for ao. After loading the statistics packages needed via
Needs "Statistics" Master" "

NonlinearRegress[data.f[t].t.
{{a.1.1}.{om.1.1}.{phi . 1}.{b . 2}}.

sity distribution, i.e., the integrand of P7(X5), (1.29), whereas CDF yields the
integral, i.e., P7 (X5) itself. With Quantile, the function P7 (X5) is inverted.

Quantile[ChiSquareDistribution[7]. 0.95]

the area in parameter space for which x2 (a) = x2 (ao) + .::1.

Figure 1.8 shows the function f [t] for a=i, om=i, phi=O, and b=O .i, as well
as the 11 data points that were obtained from f [t] with the random errors

The X2 distribution is shown in Fig. 1.9. Strictly speaking, the distribution


(1.29) is valid only for Gaussian-distributed errors Ci, but we do not expect
a large difference for our uniformly distributed errors Ci. For the correct set

, . ., z
We obtain the confidence interval for the value of X~ from
1.5 Nonlinear Fit 27

Fig. 1.8. Damped oscilla-


t tion and noisy data

o 5 10 15 20 Fig. 1.9. X density dis-


tribution with seven de-
chi2 grees of freedom

and the result of {limit [0.05] , limit[0.95]} is {2.2,14.1}. This means


28 1. Functions in Mathematica
0.2
0.14

..,;)
0.15

~
V.I
/)J // // *l
0.12

OOR
0.1

I
/
-
'\
0.05

0
11/
f L..-//
l/
0.06

0.04

v.v..:.
~ ............
-
~J ..-/'

0
0.4 0.6 0.8 I 1.2 0.9 0.92 0.94 0.96 0.98 I 1.02 1.04
a om
'INa
'CO
1 111 n nf ,,2(.n)
"" , -~
T
UTifh fho ... _h .... 1"'.... 0 i ....
r .
space (left) and with the om-b plane (right)

If one vanes the frequency om rather than the amplitude a the compen-
,. .1 ~ hrn,p rlnp~ nnt 1 ~~ .1 in thp riCTht_h~nrl nf
'rr . '0'
1

Fig. 1.10. The true values, om=1 and b=O .1, lie close to the edge of the inner
confidence region; therefore, the confidence interval should not be too nar-
row If onp nlot.~ f rt: 1 for two v~ll1p~ frmn F'i IT 1 10 ,1. ;:1..:1 ~
J

..... v ~ ...
..J"
...."" .L~ a..uu
"" ........
CLv.~,
""
..... 'v, v.uoc; ~a.u ooc;oc; .L.U
D,'
.I.' .LE)
., .,.,
.1. .1..1.
.1.. ..... 1..
Ll.
lIua.lI UVlIU ~U.L
'11
voc;o OllU.l .loc;p-

resent the data relatively well. The small number of data (N = 11) and the
large error do not permit a better fit.
A -'I' -'I 4-1. 4- 1. .1. 1 , ,. 1 .
.< ... 0 ~.... u .. ~'" u ...."'v.. J , u .. ~"'.. '" ~o LW." V'" J.VJ.

estImatmg the errors OI the parameters. une taKes the optImum parameter
set ao for one experiment and uses it to generate new, artificial data that
are fitted in turn. Repeating this for the same ao yields a set of parameter
vectors ak. Figure 1.12 shows the results of 100 iterations, using the ao from
(1.31). together with the contours from Fig. 1.10. It can be seen that in the
(a,b) projection even more than 90% of the data fall within the outer contour

I /""'\.
'" ,.,
V.1J
. l \

';:;'
.....
0.25
0.5

~
v
V
H ~
A ,.
4
-0.25
-0.5

0 2
V 4
..........."
6 8
Fig. 1.11. Two fit curves
~

lIt:u,
, ~-
I'
UV.lll
J.,J.VJ.""
lI.l.lt: VUlIt:l'
r
~Vll-
-
liour OI line a-D plOli snown
t in Fig. 1.10
1.5 Nonlinear Fit 29

Fig. 1.12. Parameter values a and


b from the fits of the artificial data
0.5 0.6 0.7 0.8 0.9 1 1.1 1.2

0, ,
take into account only the first 68 of these vectors, the last of which sets a X2
limit X~8 = x2 (a68)' All these remaining ak then lie inside the quasi-ellipsoid
2 2 '

o am e ex reme ImenslOns 0 e e IPSOl . n IS way, we can even ua y


make the statement that with 68% certainty the true vector atrue lies in a
quasi-ellipsoid that is contained in the rectangular parallelepiped

Of course, not every point a of the rectangular parallelepiped belongs to the


68% region, owing to the correlations mentioned above. Whether or not it
belon s to this re ion can be determined from its 2 a .

Exercise

+a exp

data = tvinpeak.dat

fit parameters.
30 1. Functions in M athematica

Bevington P.R., Robinson D.K. (1992) Data Reduction and Error Analysis
for the Physical Sciences. McGraw-Hill, New York

, "
Press W.H., Teukolsky S.A., Vetterling W.T., Flannery B.P. (1992) Numer-
ical Recipes in C: The Art of Scientific Computing. Cambridge University

am-

The expansion of physics equations in terms of a small quantity is an impor-

exact potential.

ysics

The electrostatic potential4>(r) of N pointlike charges ei at the positions r(i)


is given by
N

The electric field is determined by the gradient of 4>:

OX' oy' oz
When observing this potential from a long distance, Le., for Ir - I
r(i) ~ 00,

4>(r) = -
r
+ - r 3 + -rQr+O
2r 5
(1.34)
1.6 Multipole Expansion 31

N N
q = ei, P= ei r (i), Q kl =
i=l i=l

where ri i
) is the kth component of r( i) .

We want to investigate this expansion using an example of five positive and


five negative unit charges that we place in the x-y plane, randomly dis-

rpoint:={2 Random[]-1, 2 Random[]-1, O}


Do[r[i] = rpoint, {i,10}]

p1 = Graphics[Table[Line[{Drop[r[i],-1]-{O.08,O},
Drop[r[i].-1]+{O.08.0}}],{i.5}]]
=
. .


Drop[r[i+5],-1]+{O.08,O}}].{i,5}]]

Next, we use Circle [ ] to draw a circle around each symbol,

o tions] to lot all four ra hies ob-

two vectors,

The dot between two arrays of numbers - Mathematica's extended notation


for this is Dot [11,12] - effects a scalar product of the two vectors, i.e., the
sum of the products of corresponding components of the vectors. Without the
dot on the other hand the vectors would be multi lied element b element

ei = 1 and:
32 1. Functions in Mathematica

...
..
1 c:
~

1 $
0.5 Ss
""
>. 0 a:"'.....'J7
'V'J
EIb
~
S
-0.5
-1 $

-1.5
....
-... ,
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2 Fig. 1.13. Positive and negative charges
x randomly distributed in the x-y plane

pot [rh_] := Sum[1/dist[rh.r[i]]-1/dist[rh.r[i+5]].{i.5}]

We present three ways to visualize this result: first we use Plot3D to plot the
r. r .. r
r
.1
,U.l
,'I..
lJ.l.l{;; .lV.l.l.l.l V.l
.11
" ............ J'" (ld..lU
..1
~ VUlJ V.l
.'1..
lJ.l.l{;; "'" -Y A
1
,
next, we plot the contours 01 thiS mountaIn range lJy usmg (;ontourPlot;
finally, we calculate the electric field and plot it via PlotVectorField, from
the package Graphics" PlotField'. In order to see anything in the latter
case, however, one has to normalize the field, i.e., display only its direction.
The dinole and auadrunole moments can be formulated lust as easilv in
Mathematica. According to (1.35), we have
dipole = Sum[r[i] - r[i+5].{i.5}]
.. ......:.....,_r_, ._
r~-- ..r r,~" . r r .. " T~ r" __" ,.., r,o .... r ...... ,

q~wn
_.. . 'L'" ... L L .... .J .J

-~
~ .........
... L L ... .J .J

i LLL~JJ -
...... L ....'

~
' ............

-~
~ ..
v.J.~

...
........ .I.~ ........I.J
_....
'LL'L~"OJJ ,"l~,OfJ
r. _ , ..

Here, the Kronecker symbol 8kl is represented by the following expression:


.
~ .~
.LI LK==.L .L UJ

To calculate the magnitude of a vector r, which we could also express as


dist [r ,0], we use the function
ma~n[r ]=Sart[r.r]

With this, the expansion (1.34) of the potential 4>(r) can be defined immedi-
ately. In our example, there is no net charge (q = 0); therefore, the first term
pot 1 is the dipole term, and pot2 contains the quadrupole term in addition:
po'Cllr_J - Q1p0.1e.r I magnlrJ,j
pot2[r_] = pot1[r]+1/2/magn[r]A5 r.qsum.r

Here, qsum is an array of arrays, in this case a 3 x 3 matrix; r is an array


of n11Tn hPTQ 1 P :l. 'T'hp r_ nof: r 1 ..1"
...'I hv :l. rlot (.,
r. , .1 " . .r " .'1.. ,. oJ

, .~
.lV.l l.J.l{;;V.llJ'y, V.l ,0 vv .llJ.l~ a..l.l a..l
'.1 V.l

indices (= nested arrays). Therefore, in this case the quadratic form "vector
1.6 Multipole Expansion 33

conventIOn programmmg
nest two for loops:

for(j=O; j<3; j++) {


sum = sum + r[i]*qsum[i] [j]*r[j] }}

e ie =
-{D[pot[{x.y.z}] ,x] ,D[pot[{x.y.z}] .y] .D[pot[{x.y.z}] .z]}

To obtain its direction one has to divide bE:


direction = efield/magn[efield]

Results

,
randomly distributed in the x-y plane (Fig. 1.13). In this plane they gener-
ate the potential pot [ {x , y , O}] that is displayed as a "mountain range" in

Fig. 1.14. The potential .p of the ten unit charges in the plane z = 0
34 1. Functions in M athematica

-2L.o....._ _---'-_ _--....~ ._J Fig. 1.15. The same potential as in


-2 -1 0 1 2 Fi. 1.14 but dis la ed as a contour lot

Fig. 1.16. The exact po-


tential (solid curve), the
dipole term (shorf-dashed

not correctly represent the two positive maxima near the positive charges.
Even with the quadrupole correction (long-dashed curve) the approximation
.

Exercise

enerated by a current I flowin

vector potential A, from which the magnetic field B =V x A is calculated,


1.6 Multipole Expansion 35

_
_
----//////Il
- 1// / / I. 1 \\ ~\ ~\ '\ " " "," ---
\ ",,,,,, - - Fig. 1.17. The direction
... ---//// / / / I l
-10 ----//////1111 \ \ \ \ '\ " " " " ' " of the electric field of the
~\\\\'\'"''''''
ten unit charges in the
11) 11) n
v

takes a particularly simple form in spherical coordinates (r, 0, t/J), with unit
vectors er , e(J, et/J. Only its t/J component is non-zero, and for this component
or..... or
Lilt: uy J.U. gl vt:~ Lilt:

At/J (r 0) = fLo Ia [(2 - k 2


) K (k) - 2E (k)]
, 1(" Ja 2 + r + 2arsinO
2 k2
,y .........

k2 = 4ar sinO .
a2 + r + 2arsinO
2

K(k) Rllinr,icKrk-21 and E(k) Rllin'HrJ;'rk-21 are the .1

..... 'V.. u ....'V ...... uu ........... 0... ........

Calculate the magnetic field B(x, y, z) and plot its direction in the x-z
plane, using the function PlotVectorField[. .. ]. Attempt to plot the field
1:~" ........~ D :~ 4-\.. ..... ~ _.1 \.... ~ ..... :4-~\..ln no 1

nint ~applies
omy to Mamematica versions oeIOre .l.U): ~ne prOOlem tnat
Mathematica does not know how to calculate the derivatives EllipticK J and
EllipticEJ can be solved since the derivatives of the elliptic integrals can
be expressed again by elliptic integrals. The two lines
. . - - . . -- . .--
36 1. Functions in M athematica

Gradshteyn I.S., Ryzhik I.M. (1994) Table of Integrals, Series, and Products.
Academic Press, Boston, MA

ml ., ac man
Addison-Wesley, Reading, MA
Wickham-Jones T. (1994) Mathematica Graphics: Techniques & Applica-

1.7 Line Integrals

Work = force x path length. This seemingly simple equation from high school
.. ...

p t;

F= -vp. (1.37)

Algorithm and Result

s in space r

Sin[2Pi t] t}
1.7 Line Integrals 37

The first path is a spiral, the second the straight line connecting the two
points, and the third a semicircle in the x-z plane. ParametricPlot3D dis-

int[r_]:=Integrate[k[r].v[r].{t.O.l}]

cur

o O}.
38 1. Functions in M athematica

r 1

o o
where we choose s (t) = r4 = t {x, y , z} as a path from 0 to r. Except for
the si n int [r4] ields the otential ~ x z = - x + xz
We can now slightly modify the field F(r), for example to
f[{x,y,z}] = {2x y 2 + z 3, x 3, 3x z 3}
A A A A

,
now calculate the curl again, then curl [f [ {x, y , z}]] yields a value different
from 0, in agreement with the dependence of the integral on the integration

Exercises

, , ,
three line integrals and plot the absolute values of the three accelerations
Id2r/dt21 as functions of T.
. .

Literature

cations, Mineola, NY

Frequently in physics the mutual dependence of quantities is governed by


nonlinear equations that can only be solved numerically. One example of this
is t e curve 0 a van er a s as wit t e tern erature as a
parameter, which obtains physical significance through the so-called Maxwell
construction.
At low temperatures, the isotherms of the equation of state, which is

,
to be replaced by horizontal lines that in a sense bisect the loops. In order
1.8 Maxwell Construction 39

non inear equa ion a, ur ermore, con ains an in egr . n is way, one
obtains a description of the phase transition from gas to liquid.

For an ideal gas of N noninteracting classical particles with no internal de-


rees of freedom the theor of heat rovides a sim Ie relationshi between

pV = NkBT. (1.39)
Here, kB is the Boltzmann constant. Taking into account the interaction

(p + ;2) (V - b) = NkBT (1.40)

,
function of the volume V for constant temperatures T. For high temperatures,
the pressure decreases as the volume increases, whereas for low temperatures

(1.41)

Sa a
T = 27NkBb' ~
c = 3b, Pc = 27b2
(1.42)

(Ii + :2) (3V - 1) = 81' . (1.43)

, ,
i.e., over a certain range three volumes Vi, V2, and V3 correspond to each
pressure p. Fo~ thermodynamic reasons, the transition_ from the gas, with a
40 l. Functions in M athematica

Vft

Jr p( V)d
- -
V = Pt
1-
~ V3 -
-
VI) .
\
(1.44)
VI
~lJ Pt, _ga:s ~IlU
. ..nqulU.. are
. . .ly .. "
lur
.. .
au v
T-P

V
..
WllJn
VI < V < V3; one observes a two-phase mixture. Geometrically, the equa-
tion above means that the ar~a bet~een the curve p(V) and the straight line
Pt = con~tant in_the range Vi to V 2 is the same as the corresponding area
between V2 and V3 (see J:4'i~. 1.19). Usm~ Mathematzca, we want to construct
+h~ .ii.
- ~
+_h~4o ,~
. .l., ... ",,,,,, linp
-

Algorithm and Result

t'Irst, we venty l1.4~) tor tne cntiCal pomt. we enter tne van aer WaalS
equation (1.40) (NkBT = t):
.n=t:/(v-h) - ;t/v-?
....... A
~ .... ~
' ,.. ~ ....
lo 'h.n lo.nn
~ ~
.. (1 111\.
\ '/

eq1=D[p,v]==Q
eq2=D[p,{v,2}]==Q
TT , , , ,. , , ,.
nel-e, LIlt: OJJ ...... ..,,,.. au ~
,w Lel:iLl:i Lue . "'
and is executed first. We solve these equations for t and v:
sol=Solve[{eq1,eq2},{t,v}]

which results in a rule:


8 a
{{ t -> ----, v -> 3b}}
?7 h

Since the solution is not always unique, Solve yields a list of rules; hence the
double curly braces. We obtain the critical pressure by applying the inner
Dart of the rule to D,
oc = oj .sol[[1]]

with the result a/ (27 b-2).


Now we define the normalized function p(V) from (1.43):
. ., 0'" ,,,,,v -"", v 10
}lLV_J -
.... J , .... ..,
-~I
.... J _ ....

For the two-phase line we need two equations in order to determine the two
unknown volumes vi and v3 between which gas and liquid coexist. The first
.
.. ""',,"
-J
t'h",t ,~

"'1 ..
an" '" H t" nf~ r

eq3=p[v1]==p[v3]
1.8 Maxwell Construction 41
'1"'1-. ~
.&. ........
.J ~~~
""........ ..
.. 1-.~ .. ~.~ ~_~~~
v........ v
.... ~ {1 AA\
""................... ..............""............. 0 V"" \.L ..... J

eq4=p[vl]*(v3-vl)==Integrate[p[v].{v,vl.v3}]

An attempt with Solve indicates that Mathematica does not find an analytic
solutIOn. '1'heretore, we wil1 use FindRoot to obtam a numencal solutIOn. '1'0
find a reasonable result, however, the initial values of the (vi, v3) search have
to be specified rather precisely. Therefore, for temperatures T < 1 the function
plot [T _J first determines those values of v where p [v] attains its local min-
. . and ~ thp. . of thp.
and .. V~IV
1 .-t.

.. ... .. I. ~ l I r il.
'1"'1.
V"''''', V" ....... " .L ............. v .........
i' .J '" . , r. r ..'
.... v~V .... L'p LV.I
r ..... ., .,
-.PLV" ....... ".I ,V.I .. ,,-

turns three solutions; the two outer ones are suitable initial values. The final
Maxwell function then is
"Dmax[v J:= If[v < vi II v > v3. "D[V]. "D[v1]J

Thus, if v is between the solutions vi and v3, the two-phase line is returned,
otherwise it is p[v]. Fig~re 1.19 shows the result for various values of the
normalized temperature T, together with the unphysical functions 'P [v]. As
'IT _~ 1 /1.
'. iho'l '1"1(17\ in tho CT~'l
., r, I
tho 'T'ho tnn
.....
.... ..... O'

phase, and the next lower one represents the situation just at the critical
temperature. The three lowest curves show the separation into a liquid (small
, .
J.J.J.
, . .) ~mrl ~. .....
~"i' ... , . . .1- A )onu t.hp .. ~.~
..... . .1- linp 1"
.. '.J ~.nrl U~R
.....

--
1. IJ

1.5

1 ')l\ \
\ ~

\~-~
c.. 1

0.75
f\,
~.~ --
\/
/
~......-.-..

0.25

0
\/ 1 1. j 4 )

"":... .. .. 0 l\Jf
.. ~~_ ..1-." u .... ~ ..:1,,_ "'X7........ 1... T... ~ ..- ~~_ ..1-."
0 _e
,.
--
,
-s.-
,;:,
oL
~
.L
~~.
.. ~ ..

.vtJ, .v, .L
v .... ~

~ ~ ~~
~ ....

v.~tJ, v'~"',
~~"
~~..

~
-~

~~ ,
~'1'

V.otJ \ "up loU


,
-
,
,
.. ~ .. v .... ~
42 1. Functions in M athematica

Consider a quantum particle of mass m in a one-dimensional potential well


for - a <x< a,
o erWlse.
From the quantum mechanics course you know that the energy levels E of
the bound states are given by the following equations:

where x = (a/Ii)J2mVo, and q is a solution of the transcendental equation

q
Calculate and plot all energy levels en as a function of the parameter x.

Boltzmann L. (1898) Vorlesungen iiber Gastheorie. Barth, Leipzig [English


trans!. (1995) Lectures on Gas Theory. Dover, New York]

1, ew or
Schmid E.W., Spitz G., Losch W. (1990) Theoretical Physics on the Per-
sonal Computer. Springer, Berlin, Heidelberg, New York

1.9 The Best Game Strategy

from physics. Linear optimization is used mainly in economics (operations


research), yet repeatedly there are problems in physics as well that require

a payout tab e. To nd t e est game strategy, t e two opponents nee some


theorems from game theory, a field of mathematics established in the twenties
by J. von Neumann, and the Mathematica program LinearProgramming.

Mathematics

moves will be positive.


1.9 The Best Game Strategy 43

, . .,
o
1 3 1
K= -1 10 4 2
7 -2 3 7

Since the gain of R is the loss of C and vice versa, this game is called the
two-person zero-sum game. This procedure is repeated many times. At the

C, on the other hand, of course wants to minimize his losses, so he looks


for the minimum of K. Thus, for each choice i made by R, he looks for

up WI e I ea 0 c oose e co umn a Yle s e sma es oss m e


worst case. For each choice j, C would lose at worst the amount maxi Kij.
Therefore, he chooses that value of j which corresponds to minj maxi Kij,
in this case column j = 3. Using similar reasoning, R would choose the row
associated with the value max min K i.e. i = 1. With this strate the
amount K l3 = 3 would be paid to player R after each move. The limits each
player aims for have different values:

Now what does a gain of 3 mean to player R, who, with this strategy, may
expect a minimum "gain" of O? And should player C, who would have had to
count on a loss of 4 in the worst case, be satisfied with 3? Indeed, player R has
ever reason to rethink his strate as closer ins ection of the a out table
reveals that, if he randomly chooses rows 2 and 3 with the same frequency,
his gain will be at least 3 for any choice made by C. And if he slightly prefers
row 3 in the rocess he will even exceed the ain of 3. One can see from this

j
the three frequencies PI, 112, and P3 (with PI + P2 + P3 - 1), according to
which he chooses the rows without any correlation. On average, he receives

K = 2: Pi qj K ij . (1.46)
i,j
44 1. Functions in M athematica

Correspondingly, C looks for a strategy qY ... q~ that yields the value


mm max

Contrary to the deterministic game (1.45), the optimal stochastic strategies

This is the famous Minimax theorem, which J. von Neumann proved in 1926,
at the a e of 23. We want to ut the meanin of 1.49 in words: if la er R
chooses an optimal strategy p~, ,pg, then his gain after very many moves
is at least K o for any strategy ql, , q4 of player C. This means that for any
choice 4 with i > 0 and 1 + 2 + 3 + 4 = 1 we have

i,j
From this inequality, one can derive a system of four conditions, since with
o

LP?Kij > K o for all j . (1.51)

If we assume that ~ > 0 then with x . K 0 this becomes

l:X?Kij > 1 for all j . (1.52)


i

Xl,X2,X3 Xi _ ,
WI e 1m
= Koxo and the associated average gain K o are determined by a
strategy Po
minimum of c . x with the added condition KT x > b, where the latter vector

C, since with qo = Koyo one obtains


1.9 The Best Game Strategy 45

Then, analogously to (1.50) and (1.51), for any strategy P of R:

o.
i,i
This means that in the worst case player C, using an optimal strategy, will

The minimum of a linear function c . x with the added conditions KT x > b


and x > 0 can easily be determined using M athematica. For our example we

c = {1,
1, 1}
b = {1, 1, 1, 1}
k = {{o, 1, 3, 1},{-1, 10, 4, 2},{7, -2, 3, 7}}

and
LinearProgramming[c,Transpose[k],b]

Instead of searching for the maximum of b . y we can search for the


minimum of -b . y just as well. The inequality Ky < c is equivalent to

This yields the vector Yo and consequently K o = 1/(b Yo) and qo = Koyo
For our exam Ie the calculation ives the results
Po =
This means that R uses an optimal strategy if he chooses rows 2 and 3
46 1. Functions in M athematica

this matrix. For each move, the player chooses one of the four rows; at the
same ti~e, the computer selects one of the columns with the ~robabilit.ies qJ.

notice, however, that the computer wins in the long run, unless its opponent
calculates the best strategy p~ and acts accordingly. At the end of the game

Exercise
n extend the well-known arne of chance with the three s mbols
rock, paper, scissors to the four symbols rock, paper, scissors, and well. In
this version, two players each pick one of these four options and win or lose
one oint accordin to the followin rules:
s iss rs.
Paper covers well, paper wraps rock.
Scissors cut paper.
Rock smashes scissors.
Formulate a payout table for this game and use it to calculate the optimal
strategy for both players.

von Neumann J. (1928) Zur Theorie der Gesellschaftsspiele. Ann. Math.


100:295 [English transl.: Bargmann S. (1959) On the Theory of Games of
2. Linear Equations

(with the exception of the Hofstadter butterfly) in such a way that they can
be examined using predefined functions. When we deal with the electric cir-

2.1 The Quantum Oscillator


The e uation of motion of uantum mechanics the Schrodin er e uation
is linear: Every superposition of solutions is itself a solution. Therefore, the
method of separating the equation into a space- and a time-dependent part
b a roduct ansatz and later su er osin these roduct solutions is success-

,
of a linear differential equation. The solutions of this equation are wave func-
tions !P(r), which assign a complex number to every point r. More specifically,
48 2. Linear Equations

Physics
,
in the quadratic potential V(q) = mw 2q2/2. Here, q is the spatial coordinate
of the particle. In dimensionless form, the Hamiltonian of the system is

Here, the energies are measured in units of liw, momenta in units of ../limw,
and lengths in units of JIi/(mw). The eigenstates Ii) of Ho can be found in
. . .

'Pj (q) = (2 j i!0f") - e -q 21lj(q) ,


where 1lj(q) are the Hermite polynomials. We have
0_'
J

The c~ are the energies of the eigenstates of H o, and the matrix (iIHolk) is
diagonal because the eigenvalues are not degenerate.
. .
H = H o + Aq , (2.3)
and try to determine the matrix UIHlk). To do this, it is useful to write q as
. . t

v'2
where a and at have the following properties:
a J =
a 10) =0 and a Ii) = VI Ii -
1) for i > 0 . (2.5)
Consequently, the matrix representation of q in the space of the unperturbed

= ~ Vk + 15j ,k+l + ~ Vk5j ,k-1 = ~ J j + k + 15!k-jl,1 ' (2.6)


The a roximation that we will now use consists 0 de nin this in nite-
dimensional matrix for i, k = 0,1, ... , n - 1 only. The Hamiltonian H =
Ho + Aq4, or more precisely its matrix representation, is to be approximated
b an n x n matrix as well, where H o is re resented b the dia onal matrix

eigenvalues of H for different values of n.


2.1 The Quantum Oscillator 49

The construct Ihs : = rhs /; test means that the definition is to be used

q[n_]:= Table[q[j,k], {j,O,n-l}, {k,O,n-l}]

and according to (2.2) Ho is calculated as

With this, H can be written as

Results

The call / MatrixForm ields the Hamiltonian matrix

o
3 (2.7)

o 1.
2
+ 154 ).
Its eigenvalues are

discrepancies from the exact result.


50 2. Linear Equations

~
Q ~

~
8
7
>.6
~5 ~~
~ 4
3 ~
2
1 ---
0 0.2 0.4 0.6 0.8 1
ut:::i lUl'
. ,..
Fig. 2.1. Approximate val-
Lllt:
ergy eigenvalues 01 tne quan-
tum osCillator with the an-
'"
luur t:ll-

harmonicity Aq4, as a func-


lambda tion of A

How accurate is the approximation? This can be seen in Fig. 2.2 for
the example of the ground state energy co. For an anharmonicity parameter
A = 0.1, co is plotted as a function of lIn, for n = 7, ... ,20. Obviously this
function is not monotonic. Althoue:h we do not know its asvmntotic behavior
4o'h ....
WAA~
. 1.
~A~~
~"''''....
&~A 'v
~ "" non h ....
~- ~~A ~~ 'S:
'r> .1 U ...."'U
~AJ A
. 1
".
llu
- J
.
~~AAAO
4o'h ....
~AA~
.1 .

mat = N[h[n] I. lambda -) 1/10, 20];


Ii = Sort[Eigenvalues[mat]]; Ii [[1]]
f t .....
~
",h4o o'n +'h ....
WAA~
~"'p
&~AA~ . AAAO
uo:>l ......'" ~"'''' ....
&~A
')f\ o:>nrl ....
_~ 'v
~AA~
Af\.
&~.

co (20) = 0.559146327396 ... ,


co (40) = 0.559146327183 ....

Tneretore, tor n - ~u we nave an accuracy 01 aoout mne slgmncant ngures.


Higher energies can only be determined with less accuracy. We obtain
clO (20) = 17.333 ... ,
~'I'o\ ..... n .....
ClO \ <j;U} ~ , .:)iJ ~ ,

i.e., an accuracy of only three significant figures.

-
u. OJ OJ\} lOj

0.55914
-.
S
UJ n r'r'n1,.,
V.JJ7~J

0.55912 Fig. 2.2. Approximate


values for the ground
o ~~Qll state energy of the an-
harmOnIC OSCillator as a
0.06 0.08 0.1 0.12 0.14 function of the inverse
matrix dimension 1/n
lin forn=7,8, ... ,20
2.1 The Quantum Oscillator 51
T, D.' 'l1 .1, '-' -' r. , ., r. .. rpl. ,.
.......... "'0' ~ .....' ... v ....... J ,... u. .LVLU. ~~.~~... .LV.L V"".L '''-''- .L , ... ,

tne two upper energIes are representea In an entIrelY Incorrect manner. in


Fig. 2.3, on the other hand, we have included twenty levels. In this case, the
numerical solution of the eigenvalue equation yields a very precise result for
. ~. . ... . .~. ..
tne Dve loWeSt energIes. .Lne energIes, as well as tneu separatIOns, Increase as
the anharmonicity parameter ,\ increases.

10 ____

Q ----
-

_==---------
'1-/
3
2
1
~lg. ~.3. The nve lowest en-

o 0.2 0.4 0.6 0.8 1 ergy eIgenvalues as a func-


tion of the anharmonicity
lambda parameter A

Exercises

we conSIaer a quantum partICle In one UlmenSlOn In a aouOle-weu potentIal.


For the Hamiltonian we use the dimensionless form

1 nr~.w t.hp ~
.1
2. Calculate the four lowest energy levels.
3. Plot the wave functions of the four lowest levels together with the poten-
t.i~J
AI A " y y .,. y r 2 -' 4 y. ,1 L
"%. '-J'uc "au CWOU lIUC U.L '1 CW.lU '1 LJ UJ C,A-

pressIng the operators In terms ot a and ai, analogously to l~.4). Uoes


this improve the results?

T,'

Schwabl F. (1995) Quantum Mechanics. Springer, Berlin, Heidelberg, New


York
52 2. Linear Equations

Ohm's law is a linear relation between current and voltage. It is still true for
monofrequency alternating currents and alternating voltages, if capacitors
an In uc lve COl s are represen e y comp ex lmpe ances. e equa Ions
even remain valid for the general case of passive electrical networks, if one
chooses an appropriate representation for currents and voltages in complex
space. For a given frequency, they can be solved relatively easily by com-
uter and with the Fourier transformation the out ut volta e can then be

Physics

iwt

where Vo and 10 are complex quantities whose phase difference indicates how
much the current oscillation precedes or lags behind the voltage oscillation.

with a com lex im edance Z. For an ohmic resistance R for a ca acitance


C, and for an inductance L, Z is given by

Z = R, Z = -.-1 , Z = iwL , (2.11)

where R, C, and L are real quantities, measured for example in the units ohm,
farad, and henry. In an electric network, the following conservation laws, also
known as Kirchhoff's laws, are valid:
wing 0 ar e conserv i n, in
to the sum of the outgoing currents at every node.
2. Along any path, the partial voltage drops across each element add up to
the total voltage over the path.

which determines all unknown currents and voltages.


As a simple example, we consider an L-C oscillatory circuit which is con-
2.2 Electrical Circuits 53

R ...T.
~

I
Ie IL
c::>
'1'I ,., c::> T 'T
'-' 01
.LJ
Yo
01

I
r Fig. 2.4. Series connection of re-
slstance ana ~v oscUlatory Clr-
CUlt

transient, have the same frequency as the input voltage. In this case, the
. ...... .
t"

~
..
~ '0 "' . ..}.,. ".....1.-:1.......
Voltage addition: VR + Vo = Vi ,
Current conservation: IR = Ie + IL ,
.......
vnms
. .
laW.
9 P

VR - n lR,
~ Y ,- -
~..I:;.u:)

1
Vo - :-c le ,
lW
Vo = iwLIL .
.ror a given input VOltage Vi, tnese Dve equations, wnicn in tlllS simple case
are easily solved without a computer, determine the five unknowns VR, Yo,
I R , Ie, and IL. Independently of R, the magnitude of the output voltage Vo
always reaches a maximum at w = l/VLO; at this frequency the impedance
of the oscillatory circuit is infinite.
TTl 1i'1.... ') ~ . u.rO h~"o
. _1 _1 tho
h"
_1 _1" . . . If",
0' - - oJ -0 '"
capacitor 0 and an inductance L are connected in series, then the impedance
at the frequency w = l/VLO is minimal. Consequently, we expect a maximal
14-~~,", fnr thl~ !:at thl~ 'T'hl~ 1~ "1
'''-
n .....

'-'
.
r
. oJ
1
h"
'J


I.o.l,u::
t" n
'11.1 0 LWU . .
Voltage addition: fa ( R + iW~ + iwL) + Yo = V; ,

C L
R
r--t J-
~OOOO'

l
C)I

C)I
Vi C L Vo
--
C)I

~ ......11:).
I: -'i.i.J.
.... -
,.J . ~

I tlOn 01 .It--Li -lJ comoina-


tlon ana .L- -v OSCillatory
circuit
54 2. Linear Equations

urrent conservation:

resistances R, Vo becomes much larger than Vi. This can be made plausible by
the following consideration: For low frequencies, the behavior of the parallel

input signals one obtains the corresponding superposition of the output volt-
ages. In particular, one can expand any periodic input voltage Vi(t) with

(2.14)

(n)
Wn = 21t"n T to obtain an output voltage Vo Wn
output signal is given by

eq1 = {vr + vo == 1, ir == ic + iI, vr == ir r,


vo == ic/(I omega c), vo == Iomega L ill

the variable eql. With


2.2 Electrical Circuits 55

the system of equations is solved for the specified variables. Because systems
of equations generally have several solutions, Solva returns a list with lists

As an example of a non-sinusoidal input voltage Vi(t) we choose a saw-


tooth voltage with the period T, which we probe at N equidistant points in

ar
_Vi ((r-l)T)
= Vi (t r ) = N , r = 1, ... ,N ,
ourier trans ormation we 0

.(8 - 1)(r - 1)
N
or
N
1 .(8 - l)t r
Vi (t r ) = -- bs exp 21l'1~-~-

We cannot use the Fourier transformation itself here, but have to use the
inverse transformation instead, so that the sign in the argument of the ex-

N
8 = 1, ... , 2 '

The inverse transformation, which in this case is the Fourier transformation


56 2. Linear Equations

, as can a so e seen

to just a sinusoidal oscillation with the frequency W = W r .


Basically, for f < 1/2 and R = 200 S1, for example, only the multiple of
27r IT closest to W r will be filtered out. By contrast, for f > 1 and a broad
resonance all harmonics 0 27r T are included and a distorted co of the

For the second example, the series connection of R-C-L combination


and L-C oscillatory circuit (Fig. 2.5), Mathematica, again with Vi = 1, gives

omega omega

sharper the resonance


2.2 Electrical Circuits 57

-0.

0.5 1.5 2 2.5 3 0.5 1 1.5 2.5 3

output of the filter for f = 1 and R = 2700 n (right)


0.3 0.8
0.2 0.6

c
0.1
. :
.
0.4 :
'0 OJ-L.~:~+4-+-.............-+-:;...++-0---+---;--1-1--1 % 0.2 :
> -0.1 : i > 0~:------1'--~--+----:----t----1

o 0.5 1.5 2 2.5 3 0.5 1.5 2 2.5 3


tIT tIT

,
copy of the input signal that results for f = 3 and R = 5 n (right)

For R = 0, i.e., if the ohmic resistance is equal to zero and the circuit is
therefore loss-free, the denominator vanishes at

w=

first for a general element with a complex impedance Z, through which a


58 2. Linear Equations

Fig. 2.9. Magnitude of the


output voltage for the net-
work of series and parallel cir-

lon, 30n, and 90n

P = ~ (Re I (t) Re V (t) + Iml I (t) 1m V (t) )


1

= ~ (Iz Vi + IzVz)
1
=- z
where we have set Vz = ZIz at the end. For the ohmic resistance R, t e
power is accordingly ~(w) = IIR(w)1 2 R12. We compare this to the power Po,
which results if all coils and capacitors in our network are short-circuited,
i.e. i t e in ut vo ta e i is connecte nect to t e resIstor ,so t at one
gets IR = Vii R, and therefore Po = IViI 2 /(2R). The power ratio P(w)1Po
is shown in Fig. 2.10 for R = 10 f!. At both resonance frequencies the coils
and capacitors appear to be completely conductive, while at w = 1 ..jLC the

Exercises

1. Calculate and draw Vo (w).


. .

issipation in t e two resistances as a unction 0 w.


2.3 Chain Vibrations 59

0.2 Fig. 2.10. The power P(w)


dissipated in the ohmic resis-

connected directly to R

Iterature

Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Red-


wood City, CA

2.3 Chain Vibrations

the model solid can be represented by superposition of such eigenmodes.

SICS

We consider a chain consisting of pointlike masses ml and m2, which we


designate as light and heavy atoms respectively, for sake of simplicity. The
particles are to be arranged in such a way that one heavy atom follows three
i t ones. The unit cell of len th a thus contains four atoms. Onl nearest
neighbors shall interact with one another. We limit our considerations to
small displacements, Le., the forces are to be linear functions of the shifts of
the masses, as indicated in the s rin model shown in Fi 2.11.

n,
and t n be the displacements of the light atoms from their rest positions, and
60 2. Linear Equations

Fig. 2.11. Linear chain consisting of two types of atoms which are connected to
each other by elastic forces

mtSn = 1 (t n + Tn - 2s n ) , (2.17)
mt in = 1 (Un + Sn - 2tn ) ,

, ,
hold for every unit cell n E Z. For a finite chain consisting of N unit cells
we assume periodic boundary conditions, that is, we think of it as a ringlike
. .
,
invariant under the translations {Tn, Sn, tn, Un} --+ {Tn+k' Sn+k, tn+k, Un+k},
k = 1,2, ... , N, (2.17) can be solved by applying a Fourier transformation.

Xn (t) = = S (q) exp (iqan iwt) , (2.18)

where, owing to the periodic boundary conditions, q can only take the values
qv = 21rv/(Na) , v= -N/2+1, ... ,N/2. Then

ields
- 1 0 - le- iqa
21 -I 0

which is a generalized eigenvalue equation of the type

, ,
2
w (q) and the corresponding normal modes S(q) for a given value of q. In our
2.3 Chain Vibrations 61

M- 1 F8 = >'8 . (2.22)

This is an ordinary eigenvalue equation for the positive semidefinite Hermi-


tian matrix M- 1 / 2 FM- 1 / 2 with the eigenvector M1 / 2 8.
The ei enmodes X n t = 8 l qll exp iqllan iWlIlt thus obtained are par-

gously to the electrical filters (Sect. 2.2), the general solution can be ob-
tained by a superposition of the eigenmodes. From the complex conjugate of

The coefficients elll, which are not yet determined, are fixed by the initial

Algorithm and Results

The 4 x 4 matrix (2.22) does not represent any particular challenge to an


anal tical solution of the ei envalue e uation. If we consider several different
types of atoms, or the corresponding two-dimensional problem, however, the
matrices become so large that only a numerical determination of the vibra-
tion modes is ossible. We want to demonstrate the latter usin our sim Ie

choosing a = 1:
matt ={ { 2f t -ft Ot -f*Exp[-I q]}t

{ Ot -ft 2f t -f}t
{-f*Exp[I q]t Ot -ft 2f} }

case, Mathematica is still capable of specifying the eigenvalues in a general


62 2. Linear Equations

nested square and cube roots;

{x.-Pi,Pi.Pi/50}]

Flatten [ Table [
Map[{#[[1]].Sqrt[#[[2,k]]]}l. eigenlist],
{k,4}], 1]

in Fig. 2.12. As we can see, the allowed frequencies of the lattice vibrations
form four bands. The lowest branch represents the so-called acoustic phonons,

3r.::::=============1
2.5
~
bO

e
o

Fig. 2.12. The frequencies of

.. ..
..


..


.. 54(0)

53 (0)

e---- ;0
e---- .. 52 (0)

Fig. 2.13. Eigenmodes of the chain for q = 0


2.4 The Hofstadter Butterfly 63

Exercise

Investigate the two-dimensional vibrations of your single-family home. Five


equal masses m are coupled by springs, and the potential between neighboring
masses is

V (r r)
D (Ir - r 1 - a .) 2
~,J -- -2 ~ J ~J ,

the sides and the roof, and aij = V2l for the two diagonals.
Calculate the frequencies of the vibrations for small displacements and

Literature

Goldstein H. 1980 Classical Mechanics. Addison-Wesle Readin MA


Kittel C. (1996) Introduction to Solid State Physics. Wiley, New York

Linear equations can have intriguing solutions. This becomes especially ap-
parent in the case of a crystal electron in a homogeneous magnetic field. The
electron's ener s ectrum as a function of the stren th of the rna netic eld
has a complicated structure reminiscent of a butterfly. This problem was in-
vestigated in 1976 by Douglas Hofstadter. Amazingly, the differences between
rational and irrational numbers become evident in this s ectrum. We want

butterfly.
64 2. Linear Equations

We model an electron on a square lattice by localized wave functions and


matrix elements for jumps between nearest neighbors. In such a tight-binding
.. . . .

(k) = 0 (cos kxa + cos kya) , (2.25)


where a is the lattice constant, 40 is the width of the energy band, and

t e vector potenti an p is t e momentum operator. For a magnetic field of


magnitude B perpendicular to the x-y plane one can choose A = (0, Bx, 0).
Thus one obtains the Schrodinger equation

E cp (x, y) = 0 cos Ii: + 0 cos Ii: + cp (x, y) . (2.26)

Owing to the identity cos a = [exp(ia) + exp( -ia)] /2, and because the term
ex ia is the translation 0 erator that effects a shift b one lattice

Ecp(x,y) = ~O [cp(x+a,y)+cp(x-a,y)

+ ex

pIes cp(x, y) with the amplitudes at the four neighboring sites. For the y-
dependence of the wave function we assume a plane wave,

and with the dimensionless variables m = x/a and u = a2 eB/ he we finally

Here, the energy E is measured in units of 0/2. This discrete Schrodinger


equation contains only the parameters v and u. The parameter v determines
t e -com onent 0 t e momentum w i e u is t e ratio 0 t e rna netic ux
a2 B through the unit cell to a flux quantum he/e.
With this equation we have mapped a two-dimensional lattice electron
onto a particle that jumps alon a chain in a periodic cosine potential. The

,
(= 1 in units of m). Here one can already see the difference between rational
2.4 The Hofstadter Butterfly 65

The eigenstates and the corresponding energies are classified by k and v. If


one writes (2.29) in matrix form in the following manner,

with

then the q-fold iterated equation combined with (2.30), namely

Trace Mq (E) = 2coskq. (2.34)

or rational num ers u = p q t ere are at most q energy an s w IC one


can calculate, in principle, from (2.34). In the vicinity of any rational num-
ber there are numbers with arbitrarily large q as well as irrational numbers
q ~ 00, owever. onsequent y, as a unctIOn 0 u, t ere are spectra WIt
large numbers of energy bands next to each spectrum with few bands. Here,
the difference between rational and irrational numbers becomes evident in
physics.

Algorithm

1 and q - 1, but select only those p for which p and q are relatively prime.
66 2. Linear Equations

The assumption that {'l/Jm} is, for example, an odd function of m, that
is 'l/J-m = -'l/Jm, first leads us to 'l/Jo = 0 and then, taken together with the

'l/Jq/2 +r = -'l/J-q/2 - r = -'l/Jq/2-r (2.35)

en-

o o o

Ao'l/Jo = E'l/Jo , where Ao =


o 1
.(2.36)
1 0

appropriate here, we want to demonstrate briefly that the treatment of those


wave functions that are even in m leads to a very similar problem.

q
'l/Jq/2 +r = 'l/J-q/2 - r = 'l/Jq/2 - r for r = 1,2, ... , 2 - 1 . (2.37)

('l/Jo, 'l/Jl, ... , 'l/Jq/2) T = 'l/Je of the wave function has the form
2.4 The Hofstadter Butterfly 67

o
Ae 1jJe = E1jJe, where Ae = o 1

This two-part recursion formula is completed by the initial values


PI (E) = Vi - E and Po (E) =1 . (2.40)
, 0 q -
The special importance of the polynomials Pn(E), however, comes from
the fact that they form a so-called Sturm sequence: Sturm sequences contain

Po (E), PI (E), P2 (E), ... , Pq/2-1 (E) ,


then one obtains the result:
q -
is equal to c(E2 ) - c(E1 ).

C(Ei) and C(Ei+d then tell us whether there are any eigenvalues between Ei
and Ei+l. The region in which any energy eigenvalues can be found at all
. .

IE - aiil < ~ laijl (2.41)


j=l,j:#

j=l,j#i ij
conclude that the eigenvalues fall between -4 and 4.
68 2. Linear Equations

P2 - Po
Pn (E) = (Vn - 1 - E) Pn-l (E) - Pn-2 (E) for n = 3,4, ... , ~ ,

urm sequ nces,


and (2.42), are almost identical to the Harper equation itself, for (2.29) leads
to the following relations for the odd wave functions "p-m = -"pm with the

the P loop, where a(p, q) is varied, the ie loop, in which the energy changes
between -4 and 4, and the inner loop over m, which is used to determine

for(q = 4; q < qmax; q+=2)


{
2.4 The Hofstadter Butterfly 69

{
e = 8.0*ie/MAXY - 4.0 - 4.0/MAXY
n = 0;
polyold = 1.0; poly = 2.0*cos(si a) - e;
if( polyold*poly < 0.0 ) n++

fore m = 2; m < q/2; m++ )

polyold = poly; poly = polynev;


}

eigenfunctions has been left out here.


if(n > nold) action;

,
((1- E) values to a data file. The function gcd (p q) used in the third line of
J

the program calculates the greatest common divisor of p and q.

The result of this program can be seen in Fig. 2.14. The energy is plotted
on the vertical axis, the parameter a on the horizontal one. The ener y is

small interval, a point is plotted at the corresponding position.


It is surprising and fascinating what a complex, delicate, and appealing
. .

, ,
to any rational number a = min (m and n relatively prime) with a small
70 2. Linear Equations

flux per unit cell

Fi . 2.14. Ei envalues of the Har er e uation as a function of q = Ba 2


i.e. of the ma netic flux throu h the unit cell in units of the flux uantum

denominator n there e also others with a large denominator, there will al-
ways be a large number of bands next to those values of (J that correspond
o a sm enomma or. ny lrra lon num er can e apprOXlma e y a
sequence of rational numbers with increasing denominators. Consequently,
there will always be an infinite number of energy bands next to an irrational
number. This results in the artistic drawing which, given infinite resolution,
resists our ima ination.

Exercise

butterfly and conceive an algorithm which bridges the many large holes.

trons in Rational and Irrational Magnetic Fields. Phys. Rev. B 14:2239


2.5 The Hubbard Model 71

,
statements. Add to this a considerable mathematical apparatus in which the
concept of states has to be introduced and operators have to be explained.

only be occupied once. In this space of the multiparticle wave functions, the
Hamiltonian can be represented as a matrix whose eigenvalues specify the
ener ies of the stationar states.

analytic methods. But even a numerical solution is not easy to obtain. The
size of the system and the increase in the number of degrees of freedom turn

x q m-m mu p y m, w
sider an electron gas in a crystal lattice. In dealing with this problem, we
have to take into acc?unt both the repulsive Coulomb interaction between
the electrons and their interaction with the ion cores. A simplified description
otIS SItuatIOn, w IC stl contams a t e essentla e ements, was su este
in 1963 by J. Hubbard. Presently this model is being discussed in connec-
tion with high-temperature superconductivity. It is, however, still uncertain
whether this model exhibits superconductivity at all.

In doing this, however, we have to limit ourselves to a few particles.

Ph sics

annihilation operators, and the states can be generated by applying operators


72 2. Linear Equations

annihilation operators as well, so that the Hamiltonian matrix can eventually


be constructed algebraically.

e vacuum.
ctct ... ct N
10) , (2.43)

(2.44)

(2.45)

result is O. The adjoint operator Ck annihilates cpk(r) if present; otherwise,


the result is 0 again. The Pauli exclusion principle follows from ctct = 0,

, k
of electrons localized at lattice sites. The index k contains the number of the
site, and the quantum number for the z-component of the spin, represented

(2.46)
If two electrons occu osed to feel the
Coulomb repulsion
Unktnk.J,. . (2.47)

, ,q

the magnitudes of the kinetic and potential energy respectively.


2.5 The Hubbard Model 73

M
H = -t (2.48)
k=l u

with Ck+l,u = cl,u and CM+I,u = Cl u ' For the order of the single-particle
states, we choose

Thus every multiparticle state can be described by the occupancy numbers


of the single-particle states. Then we get, for example:

ct+ 1{1,0, ... ,O}, {O, ... ,0, I}) = ct+cttCk+ 10)
= -ct t
c c
t

and

It M+
= -ctt 10) + cl t ck+ cM+ 10)
t
- It
= -1{1,0, ... ,O}, {O, ... ,O})

Generally, when applying clu or Cku to a state

the number of particles to the left of ku determines the sign. Therefore we


define the sign function:

The function produces as many factors -1 as there are non-zero entries in


n in front of the position ku. This fact allows us to write the effect of the
74 2. Linear Equations

Cku In} = nkusign (kG", n) I{ nIt,, 0, ... , nM.tJ} , (2.52)

The following quantities are conserved in the Hubbard model: the number of
particles with positive (Nt) and negative (N.J..) spins, the quantum number
. . .. .

be reduced to submatrices with a maximum size of 3 x 3.


Here, we only want to consider Nt and N.J.. as conserved quantities. Also,

Once again, we want to use Mathematica to concisely formulate the repre-

s[arg] , where arg = {{nIt,, nMt} , {nI.J..,"" nM.J..}} (2.53)


an nku E e nee t e ea er s ecause we ave to states
and multiply them by scalars. If we were to perform these operations on
the list arg itself, we would get incorrect results. The main manipulations,
however, concern the argument of s. For example, one obtains nku from

After specifying the numbers M, Nt, and N.J.. we use the functions
Permutations [. .. ] and Table [. .. ] to generate the list index, which con-

index = {{{1,1,O}, {1,O,O}}, {{1,1,O}, {O,1,O}},

{{1,1,O}, {O,O,1}}, {{1,O,1}, {1,O,O}},

{{1,O,1}, {O,1,O}}, {{1,O,1}, {O,O,1}},


2.5 The Hubbard Model 75

{{O,l,l}, {O,O,l}}}

The operator ct has to generate a 1 in the right spot in the argument of s.

*
s [plus [k, sigma] [arg]]

number 0 as well:
cdagger[k_,sigma_] [0]:= 0

we still need the operators nklT:


n[k_,si a_] [0]:=

Then the Hamiltonian (2.48) of the Hubbard chain can simply be written as

, ,
cdagger [k+l, sigma] [c [k, sigma] [vector]] ,
{k,sites},{sigma,2} ]+
u*Sum[n[k,l] [n[k,2] [vector]] ,{k,sites}]

Here, the length M of the chain is designated by sites. In order to 0 tain


the Hamiltonian matrix, we need the scalar products (niIHlnj) of Ini) with
Hlnj). Since our multiparticle states In) are orthonormal, we only have to
e ne t e inearit 0 t e sca ar ro uct:
scalarproduct[a_,O]:= 0
scalarproduct[a_,b_ + c_]:=
76 2. Linear Equations

h = (hlist = Table[H[s[index[[j]]]]. {j. end}];


Table[ scalarproduct[ s[index[[i]]]. hlist[[j]]].
{i.end}. {.end}])

g[uu_]:= Sort[Thread[ Eigensystem[


N[ h /. {t -> 1.0. u -> uu} ]]]][[1.2]]

k=l {n}

Mathematica's version of the right-hand side of (2.54) is

Since the sums are interchangeable and can be regarded as scalar products,

Results
2.5 The Hubbard Model 77

2u
, , , 3

Coulomb energy and kinetic energy. For U = 0, there is no interaction be-


tween the electrons, so we can calculate the energy levels simply by filling

-2

U/t for M = 3, Nt = 2, and N~ = 1


78 2. Linear Equations

fivefold degenerate: 2 = 0,
twofold degenerate: 3 = 3t.

model. The average double occupancy rate in the ground state for M = 4
sites and the so-called half-filled case, i.e., Nt + N~ = M (in this specific
. ..

Hubbard ring with M = 6 sites, Nt = 3, and N~ 3. As moderate as


these numbers may seem, the number of states strongly increases with M,
. 6 6_

asM~oo

and compare the result to the corresponding values for M = 6. Surprisingly,


the two curves are not very far apart at all, as can be seen in Fig. 2.18.
2.5 The Hubbard Model 79

Fig. 2.16. Average double occu-


o 2 3 4 5 6 pancy in the ground state as a func-

U/t

-0.4,..-------........--..--------......

....
(/)

8. -0.8

e.o
II)
-1
Fi . 2.18. Ground state ener er
site for the half-filled band. The
o 2 3 4 5 6 dashed curve is the exact result for
M ~ 00, the solid curve gives the
80 2. Linear Equations
...,.
' - & 0 ....

The z-component of the spin operator at the site i can be expressed by the
particle number operators nit and nq: Sf = (nit - ni.JJ/2. For the ground
I _\ 1". L TT." , .J.1 ,L 1I..r A .J 1\ T 1\ T n '
i:)IJaIJ'lJ IY I VI. IJU'lJ .u
., VVI.IJ.U .U'.J. "% i:)J.IJ'lJi:) a u u J. Yi J. YJ. .&I,
.',

the spin correlations (11M) ~~:1 (glSf Sf+llg) and (11M) E~:l (glSf Sf+2Ig)
as a function of U It.

TO
,~uu..L'lJ

Hirsch J.E. (1985) Two-dimensional Hubbard Model: Numerical Simulation


Study. Phys. Rev. B 31:4403
T TT roo.
.L.L. " " . ,
.LJU.L
rt .,
11 nn<l \
oJ .L:.J. \
1.
,UaIJ.L;:)
.1.
T T':'
-
.L0:70:7~)
T':'. Y". ... Jr ., 1' .
.LV.L
r'\,

~

tum ~ystems. lJomputers III PhYSICS 7:4UU


Montorsi A. (Ed.) (1992) The Hubbard Model: A Reprint Volume. World
Scientific, Singapore
3. Iterations

1"1.
.. ,. .
Ul a ;:seL Ul
. ,.
LIlalJ l:unven gIven InpUlJ valUeS lJO
,. .
U.l~U
. . .
output values. Now if the output itself is part of the domain of the function
considered, it can become an input in turn, and the function returns new
output values. This process can then be repeated indefinitely. While there
are otten no analytic methods to calculate the structural properties of such
iterations of the form Xt+l = f(Xt), they are easily generated on the com-
puter. Obviously, one just has to apply the same function f(x) to the result
repeatedly. We want to demonstrate this with a few examples.

3.1 Population Dynamics

Arguably, the best-known IteratIOn ot a nonlInear tunctIOn IS the so-called


logistic map. It is a simple parabola that projects the real numbers of the unit
interval onto themselves. We want to present it here because every scientist
should know the properties of such an elementary iteration.
A simnle mechanism leads to comnlex behavior - this is the result of
+1-.1'
U~ ' ..
..l ,. . ,,~ '" . , .
..... v~
1". . . A 1+1-.".......1-. ",
v~. . ~
"''''1' '-'J
" .... 1... .....
....... 'V
'"

'-' ........
u

few analytic results on this, anyone can easily reproduce the iteration with a
pocket calculator. For certain parameter values of the parabola the iterated
, . ,
.
.
: .,
Ul LU
.~

-
.
1::)
..l 'n t1-.o "n't
.
.Y
.. .Yc;
1 'n o:>n
. ~,.. . ,.
Ul LIle OlJa.l'Lulg Value Ul
'1'1-.0 00.

'
v ~

the iteration. A well-defined function definition yields a sequence of numbers


, , . . 1;:S
.. . .
that is practically unpredictable even for a small initial uncertainty. Such a
~ .... IPol u,(;'1I(;.'
.. . .
quantItIes that can be calculated wIth the computer are not just
~ome
the result of a mathematical folly; rather, one finds these numbers in many
experiments near the transition from regular to chaotic behavior. Such a
universality of quantitative values is an additional fascinating aspect of this
.

82 3. Iterations

We consider the iteration


X n +l = 4rxn (1 - xn ) =f (x n ) , n = 0,1,2,3, ... , (3.1)

hulst, in a work on population dynamics. Here, X n is iterated in the interval


[0, 1], and r is a parameter that can be varied in the range [0, 1] as well.
. .. . .

In this model, X n is proportional to the population density of a species


at time n. Its growth is described by a linear contribution 4rx n which,

If neighboring values differ only by small amounts, then n and


Xn Xn can
be extended to real numbers in a continuous way. If we set

then (3.1) becomes an approximation of the differential equation


dx 2
dn
with the solution
4r -1
x (n) = -----~---

00

1/4 all initial values x(O) > lead to the value X oo = 1 - 1/(4r). Like
the discrete iteration, this equation has a phase transition at ro = 1/4
,

. .. .

o
we have for small en:
3.1 Population Dynamics 83

Therefore, the perturbation co explodes for If'(x*)1 > 1, which corresponds


to T > TI = 3/4. We will see that, in this case, the X n jump back and forth
between the values x* and x* after a few ste s:

(3.3)

T, ~ Too - tS (3.4)
'
From this we can conclude
I - 1-1
1-+00 T'+I - Tl

The number tS is called the Feigenbaum constant and has the value tS

,
extremely close values separate after just a few iterations and jump around
in the chaotic bands seemingly independently. For a quantitative characteri-
. .
(3.6)
The parameter ,\ is called the Lyapunov exponent; it is a measure of the

(3.7)
84 3. Iterations

immediately gets

Algorithm

With Mathematica one can obtain an n-fold iteration of a given function,


such as f x_ = 4 r x i-x sim usin
iterf[n_]:= Nest[f,x,n]

The determination of the bifurcation

2 Y ovn w
unknown variables x* and r" either by hand or by using the M athematica
function FindRoot. But we were unable to determine higher r,
values this

Now again, solving the equation

numerically is not easy. Since this equation has 2' - 1 additional fixed points,
the function oscillates very rapidly and FindRoot fails. But there is a trick:

number of Rs in the l-sequence is odd, or by R if it is even. For l = 2, the


3.1 Population Dynamics 85
,.I",.. hl~......... .., _1 rv Drv D ....... ,.1 4- l-.~~ 1 rvDT D .... ~ rvD . ,L D

~ .
l' or t -
~ J .. " ..' 4....

one gets {> J:f,I H H f-oft.


.1,
" " . . " ' ' ' ' ' . . '"
~
........ ' 4 u .......... "" .. "'.&oJ" "" UU "-' .. " JUDU VU.'V """.

The inverse iteration is most easily performed in a coordinate system


whose origin is at (x, y) = (1/2,1/2) and whose two axes are scaled by a
. . . p . . .
:mcn tnat tne peaK or tne paraOOla in tne new system is at
. A

(0,1). In this coordinate system, the original parabola f(x) = 4rx(I - x)


takes the form
J
n ft\ -
,-,,/
1 "t 2
r -"

1
II l:lnrl ... l:l ....O .... "ll:ltorl ,,; l:l
r

JL = r (4r - 2) or r = ~ (1 + viI + 4JL) .


We designate the left branch of the narabola bv or.(E) and the rie:ht one bv
9R(e). Then the superstable orbit for l = 2 obeys the equation

9R (9L (9R (1))) =0


""yo

1 = 9ii (91:"1
1
(9ii 1 (0)))
with
.1 , /1- 11
ana 9L
. .1 /1- 11
.
9R ~'fJ) ~'fJ)
V JL V JL
This finally leads to the following equation for JL:
I
a = 1/V a + ..v/ a - "fa (3.9)

which can be solved by iteration or by using FindRoot. The sequence CRLR


determines the signs of the nested roots in (3.9). After the initial CR, which
does not enter the eauation above L vields a nositive and R a negative sign.
This holds for all superstable periodic orbits. Thus, the orbit of period 5,
with the sequence CRLRR, which is located between chaotic bands, is found
at a a value that obevs the followine: eauation:
I f

JL=yJL+VJL-VJL-YP;
We have programmed the generation of the sequence in Mathematica in the
foP w~.v
., For p~("h ., .1. .1 R (T,) WI"
. t.hp mnnhpr~ 1 (I)).
, , t.hp ~p_
~
, "
quence of length 2n is stored as a list period [n] . Initially we define the list
period[1] = {c, 1} for n = 1, and the doubling of the sequence is done by
per1odln_J:= per1odlnJ-
Join [period [n-l], correct[period[n-l]]]
86 3. Iterations

sum is even.
correct[list_]:=Block[{sum=O,li=list,I=Length[list]},
Do[sum+=li[[i]],{i,2,1}];
If [OddQ [sum] , Ii [[1]] =0, Ii [[1]] =1] ;
Ii]

prec=30
maxit=30

In order to generate and display the orbits XO, Xl , X2 , X3, for all parameters
r (or J.t), one should use a fast programming language, if possible, since each
value of r requires about 1000 iterations. In principle, however, this is very

until the X n have come very close to the attractor. Then, one calculates
Xn ,
1000 additional values of X n , transforms them into the y-coordinate of the

xit = 4.*r*xit*(l.-xit);
putpixel( r*MAII, (l.-xit)*MAIY,WHITE);

following function:
3.1 Population Dynamics 87

}
getch();getch();clearviewport();return;
}

Results

fixed points of the fourfold iterated function f(x). These can be seen in
Fig. 3.2. The function f(4)(x) intersects the straight line y = x eight times,
but onl four of those are stable fixed oints. As T is increased attractors ith
, ...
Too = 0.89 .... This is clearly visible in Figs. 3.3 and 3.4, in which 1000
Xn values are plotted for each value of T, after an initial transition period

0.8

0.7
,....,
c:
~ 0.6

Fig. 3.1. Iteration start-


ing from Xo = 0.65 using
the parameter r = 0.87.
The X n values move to-
wards an attractor of pe-
n
riod 4
88 3. Iterations

I...
I

I
~ L-----------:t:----~
.: ~~m; .. .;0; _-.... N ;;..,;;.~. ~~_:o-.. . . . . . . ~-. ~'~ ~_ ....

below a five-cycle; though there is just one band there, one still sees the five
peaks of the adjacent cycle. It can be shown that only one band with density

exists for r = 1. In Fig. 3.4, in the chaotic region, one sees many windows with

baum constant 8. To this end, we calculate the parameters Rl, at which there
3.1 Population Dynamics 89

0. .

Fi . 3.4. A close-u for T between 0.88 and 1

a parameter value T ~ 0.934,


just below the window with
period 5
90 3. Iterations
1
/
/
./ ........... /
0.8

/
/ V /\
0.6

/ /
/ \ \
f\A
~.
I / \
I /

0.2
//
1/ \
\
oV 0.2 0.4 0.6 0.8 1
Fig. 3.6. Superstable four-cycle
with r = 0.874640
1 /
/'
" /

0.8

0.6
/
/ V
/ \
"

"

0.4 I / \
I / \

0.2
/~
1/
\ '(

\ , Fi~. 3.7. Three chaotic bands for


0V r = 0.9642, just above the large
0.2 0.4 0.6 0.8 1 window with the three-cycle

are
..
VI. LJUlt:) or .?~I II II
.. - - .1 ~
,(.'. I lSI 19 tne TTlPT 'lnrl~ or symoollc aynamlcs
. . . . . .
-0;-

and inverse iteration we find the R, with a precision of 30 digits, of which


only 12 are printed here:
fl. ~ 11 "'...,,,....
'.LV ,
Ru = 0.892486401027 ,
R12 = 0.892486414339 ,
R.o
'~u
o on.n A 0'"'1.1 71 QO
li14 - U.XUIAW";A 1'(~Ul ,

R15 = 0.892486417932 .
3.1 Population Dynamics 91

we find the following approximate values for ~:

~ = 4.669201134601

~12 = 4.669201587522 ,
~13 = 4.669201604512 ,

~15 = 4.669201608892 .
From this we estimate that we have calculated ~ to 9 digits. The extrapolation

m y, we want to mvestIgate a seemmg y SImp e questlOn: gIven Xo =


1/3 and r = 97/100, what is the value of XlOO? This seems to be easy to
answer; with

the command
Nest[h, N[1/3],100]

n y m ,prec ,
can specify the precision via prec. Now Mathematica reduces the calculated
precision after each step until, finally, the variable X n is set to the value 0
92 3. Iterations
An
..
.
..
..
.
....

. .
. .. ..". n... rn1~ ,.

....
.: &5. u.o. ~ oUt:: ~" VJ.

..
. XIOO for r = 97/100 as a

.. function of the precision


. with which the calculation

(\ III 111111111111
.... is performed. The vertical
axis e:ives the number of
o 20 40 60 80 100 digits to which Mathemat-
ica calculates the result of
precision of the calculation the iteration

Exercises

1. Calculate the Lvapunov exponent for the loe:istic map (3.1) as a function
nf tho 'I"
r
n. T , . ,. ,1 , . 1 1
~. ~11 ~dt;11 1 J11L~J VdJ 11J L11~ <..I' L11~J~ dJ~ W '0 WJL11 _..- -

stable periodic orbits. Any such orbit starts with the symbolic dynamic
CRL. Therefore, there are at most four possibilities for a five-cycle:
rY~T~~ rY~T~T rY~TT~ _, rY~TTT r. r, .,_.,. . .
V.lI,.LJ.lI,.lt" V ,v auu v . ,-,Ut;; VJ. LUt::Ot;; ..- J.O

not realIzed, however. lJalculate the parameter values ot the remammg


three orbits of period five.

T -, ---
Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Red-
wood City, CA
'Q ... ;T; .... U 110QII\ ("'l'h ........'" "('XT. _,.J CI .r> roo

Jom fi.-J., .l\.orSCn fi.J. \1~~LJ:) .n;.UlS: i\. rrogram \..Jouecuon IOr "(;ne C"\..J.
Springer, Berlin, Heidelberg, New York
Ott E. (1993) Chaos in Dynamical Systems. Cambridge University Press,
~
\ .:.:ITrJ.U5t::,
_y _r.
l''1ew lurK
Peite:en H.O.. Saune D. (1988) The Science of Fractal Imae:es. Snrinlrer.
Berlin, Heidelberg, New York
Schroeder M. (1991) Fractals, Chaos, Power Laws: Minutes from an Infinite
Paradise. W.H. Freeman. New York
, oo~,., n . . . t:lHllnQ AnT
n ~,
H r.! (1 .,
1

heim, New York


3.2 The Frenkel-Kontorova Model 93

potential. We investigate only the rest positions of the chain elements. Both
the spring forces and the external forces want to impose a distance of their

can take a large variety of forms.

Ph sics

between neighboring particles, on the other. Then the energy of a long seg-
ment of the chain containing the sites XM+l, XM+2,' .. ' XN is given by

n=M+l
All lengths x are measured in units of the period of the external potential,
.,
v (x + 1) = V (x) . (3.11)
In the rest position, all forces on any given particle cancel each other. There-

---=V (3.12
8x n
With the definition

this leads to

or, transformed to the inverse recursion,


94 3. Iterations

Pn-l = Pn - V' (xn-d . (3.15)


From (xo,Po) - equivalent to this is the specification of (x_I, xo) - one ob-
. .

of a continuous dynamic in three-dimensional phase space.


So far, the potentials V and W have not been specified, but now they
.. .

(3.16)
K determines the strength of the external potential, and u is the distance
between the particles for K =
0 in units of the period of the potential. We
slightly modify (3.13), which yields Pn = X n - X n -l - u, by setting

Then, instead of (3.14), we obtain


K

X n+l = X n + Pn+l . (3.18)


This mapping, which is termed "standard map" or "Chirikov map" in the

N 1 N 1 2
H MN = K L 2 (1-cos27rX n ) + L 2 (Pn - u) . (3.19)
n=M 1 (27r) n=M 1

or gIven parame ers e average energy per par lC e IS

h= lim N -1 MHMN' (3.20)


N-M-too
3.2 The Frenkel-Kontorova Model 95

cles:

If a state is periodic relative to the lattice (a commensurate state), there are


integers P and Q, with P and Q relatively prime, and xn+Q = X n + P. This
leads to
W=

Therefore, a commensurate state has a rational mean particle distance w. A


state with an irrational w, on the other hand, does not lock in to the lattice,
which affects some other h sical ro erties as well. Here as in the case of
the Hofstadter butterfly, physics distinguishes between rational and irrational
numbers!

Programming the mapping (3.18) is very easy. Since we are dealing with
numerical manipulations, we define pi=N[Pi] in Mathematica and define the

t[{x_,p_}] = {x + p + k/(2 pi) Sin[2 pi x],


p + k/(2 pi) Sin[2 pi x]}

The result of list [ ] is a list of nmax+l points in the x-p plane, which
describes the physical state for a given set of initial values Xo and Po =

xlist[xO_,pO_] := Map[First,list[xO,pO]]

individual coordinates via Map:


96 3. Iterations

The phase-space diagram is generated with ListPlot. The energy and wind-
ing number are easily calculated from the state 111 = list [xO ,pO]:

vind[xO_:.0838,pO_]:=
( v1=xlist [xO,pO]; (v1 [[-1]] - v1 [[1]]) /nmax)

pnev = p+K/2./pi*sin(2.*pi*x);
xnev = x+pnev;

time in this inner loop, where these commands are executed very frequently,
but should be replaced by constants. In our program, however, the graphics

xs = fmod(xnev,1.)*xmax+10;
ys = fmod(pnev,1.)*ymax+100;

VIa

putpixel(xs,ys,color);

For each call, a new color is selected:


color = random getmaxcolor +1;

In this way, a display with different orbits in different colors is generated on


the screen, each one representing one state.

Results

n, n
This picture is independent of the ratio (J of competing length scales, since
3.2 The Frenkel-Kontorova Model 97

Fig. 3.9. Orbits in the x-p plane. On the workstation, a new starting point can be
selected b a mouse click and the resultin orbit is lotted in a new color

this parameter is not used in the iterated function. Each orbit has a winding
number w, which depends on the starting point and the periodic potential,
but not on u. The equilibrium constant u shows up only in the energy per

K
211"
2 + -21 (Pn - u)
(1 - cos (211"x n
2

(xn,Pn). Around these commensurate states, one sees closed orbits, Le., one-
dimensional ones. These states look almost the same as their commensurate
relatives in the centers of the orbits but each x oscillates about the corre-
98 3. Iterations

Mod[t[t[t[t[t[{xO,pO}]]]]],1] == {xO,pO}

w = 0.4 and a slightly higher energy than the periodic state. Figure 3.11
shows the quasiperiodic state in configuration space. For the particle at the

after Q = 5 iterations. The oscillation can be seen even better in Fig. 3.12,
where the X n are plotted as a function of n. In addition to the period with

ex 0 e zero- an one- Imension or i s, ig. . a so con ams s a es


that fill entire areas. Such orbits jump around within the drawing window in a
chaotic manner. Some orbits obviously span the entire range of x and p values.
The latter is not true for small values of K. For K < K c = 0.971635 ..., there
are one-dimensional orbits that traverse the entire icture horizontall so-
called KAM orbits). It can be shown that chaotic orbits cannot cross the
one-dimensional ones. Consequently, they are limited to a p interval between
two KAM orbits. At K the last KAM orbit vanishes - narnel the one
"
We are, however, not only interested in the properties of the standard
map, but are also looking for the state with the lowest energy for a given

0.5
0.475
0.45

0.375 Fig. 3.10. Quasiperi-


0.35 odic orbit in phase space

x
3.2 The Frenkel-Kontorova Model 99

0.05 ~ 1\ ~ 1\
I \ I \ I \ I \
0.04 I' I \ I , I \
0.03
, I
I

.
0.02

0.01
,I }. J \ 1 \I \\1 Fig. 3.11. The same quasi-
,.-
.or ~4-~4-~ ~~ : _ ...,:_
~u~u..... ~~~_:
'> 1 fl
'1,
11 \1 If} &0' .., . . . .

"-
V n
~
1
&
-., "1
~
A
~

L1CU
. . ...Y
~,
VLl

\;L; J
lIV'p VI. till" ,.- -


no

V.U

0.6
.-...
=
'-'
>< 04

n_
v.~
~'Ig. 3.~A!:. Tne QlSplacement

X (modulo 1) of the nth par-
0 tide is plotted for the same
0 20 40 60 80 100 function as in Fie:s. 3.10 and
n 3.11

which we will not discuss here (see, e.g., Griffiths). Figure 3.13 shows h(xo,Po)
. .
m a Sllce or tne Xo Po plane lOr Xo nxea at tne valUe U.UOJO ana u - ~/tJ. ~ne
~

corresDondine: windine: numbers w can be seen in Fie:. 3.14. In the interval


shown, h reaches a minimum at Po ~ 0.35. If we want to find the global
minimum of the energy, we have to scan the function h(xo,Po) in the entire
Xn-f)o plane. At the minimum. w appears to be "locked" into the value w =
~ n.A. If tho .- . .. nf h( 'r'~ ~ !:llnrl tho ..1,' . ..1,' ..... \
, 'v'r v / I. ~ ~

number w are determined for all values of u, w(u) exhibits a fascinating


behavior, which is also called the devil's staircase: w "locks" into each rational

. PIn ;n otono n .
1. ..l.Ll..

, , I~ -.- .
_1

..
.:lIO
~
('1,
&
1" v,
.
W ~ U) Uc:G:5 aU
n
VI IS Lel'lS , aUU ",vU .. '~~U aUY LWV ISLel'lS

LUel-e lIS

agaIn an mfinite number of steps. Nevertheless, w(u) is contmuousj for all


irrational winding numbers there is a u value and a corresponding ground
state. This behavior can be proven mathematically.
The tunctlOn w{u), WhiCh resists all imagination, results trom the com-
petition of two lengths. The commensurate ground states belonging to the
rational values of w correspond to individual points in the x-p plane, while it
can be shown that the incommensurate ground states do not correspond to
area-coverin2' chaotic orbits' rather thev corresDond exdusivelv to lines. As a
o~..:In .,.,.,.,,+n " .... .,.,. 1.. n ...1. .J +1..n . 1
~&~ ..... &&'V'uv, v"-"&& ",v
~~
U&&V
.-
without changing their energy.
100 3. Iterations


f\ f\')O

0.028

>.
tlO 0.027
~
o 0.026


0.025
U.U:l4

_.
~ Ig. Jnergy 01 a
O).~O).
~ ~

-
u.~ U.~.J U .J U .J.J U ... lOree-nee state wltn u -
0.4 and initial value Xo =
pO 0.0838 as a function of po

f\,
0.475
....
0 0.45
~

-!3
tlO
.5
0.425
nA
v.
:a
.5 0.375
~
0.35

_. -
~ 11::). O).~<:I:.
, , ..
Ul:S-
0.325
lianCe W OeliWeen neign-
0.2 0.25 0.3 0.35 0.4 boring particles for the
force-free states shown in
pO Fi~. 3.13

Exercise

For different values of K from (3.18), plot orbits in the x-p plane. For K = 0,
, ,.
von ~l ~ .U he ahle t.o nr;:J,w t.hem hv h::mrl 0'
~
how t.he 1 IU. L1.:"i.

the so-called KAM orbits, turn into islands or chaotic orbits as K increases;
calculate the winding numbers of the remaining KAM orbits. Attempt to find
the 1:l.Cl.t. ., ..1 orhit. in~t.' 1'. K.
v

Literature

JodI H.-J., Korsch H.J. (1994) Chaos: A Program Collection for the PC.
Sorinf!er Berlin. Heidelberf!, New York
Ott E. (1993) Chaos in Dynamical Systems. Cambridge University Press,
Cambridge, New York
Schuster H.G. (1995) Deterministic Chaos: An Introduction. VCH Wein-
.r<
u-
ho;1'Y1
'n->"
, l\TonT Vnl"lr
............
.n..D.
r .. ""'''''' ..... ,
~ .L::1::1U)
r-.
r r -
, TF ..... .. ,.
Vi
.r< T

mensurate Phase Transitions. In: van Beijeren H. (Ed.) Fundamental


3.3 Fractal Lattices 101

Greene J.M. (1979) A Method for Determining a Stochastic Transition. J.


Math. Phys. 20:1183

3.3 Fractal Lattices

so-called fractal with a dimension D = log 3/ log 2 = 1.58 .... Surprisingly,


fractals are formed very frequently in nature. Coastlines, mountain ranges,
I I f r' k ri n w I
,
geometric game, in this section we will learn about aggregates and percolation
clusters as examples of these remarkable self-similar objects.

Ph sics

The spatial dimension D of an object can be determined from the relation


between the number of its components that make up its mass M and its
linear dimension L:

Thus, by comparing the masses of two similar cubes with sides L and 2L,
one obtains

M1
with D = 3. For squares, the result is obviously D = 2, and for lines D = 1.

(3.25)

D =- lim ---"-'-
e~O
(3.26)
102 3. Iterations

square an e or a ine.
So, if we want to determine the length of a border on a map, for example,
we can take a small ruler of length e and determine the number N (e) of steps
n . n, we wou expec
L = eN (e) (3.27)

Portuguese have determined the same border to be 1214 km long. A smaller


ruler e apparently requires more steps than L / e to cover the border, therefore,

border is a fractal with 1 < D < 2; therefore, (3.27) yields L ex e1 - D , Le.,


a length that seems to diverge as e -+ o. The border does not have a well-

arger an e sma e e.g., e surveyor s ro s use e


largest length involved (e.g., the size of Portugal).
Another simple example, in which the fractal dimension D does not agree
with the embedding dimension d, that is, the dimension of the space in which
the ob .ect is ocate is a ran om motion in d- imensional s ace. This random
walk, as it is commonly called, is also discussed as a simple model of a polymer
molecule that consists of a large number of monomers. We assume in this
discussion that the distance between ad acent monomers is constant but

, a
are random vectors, whose properties are easily calculated. If (...) denotes
the average over many molecular configurations, we have:

where a is the distance between adjacent monomers. For the vector R between
the beginning and end of a molecule consisting of N + 1 monomers, we have

i=1

and therefore

i=1

and

i=1 j=1 i=1 i:h


3.3 Fractal Lattices 103

an
. .
ImenSlOn

an consequen y, u s i n g , uc a ran om wa, ere ore, is


always a two-dimensional object, independent of the dimension d of the space
in which it is generated. The fractal dimension is reduced, however, if the size
of the individual monomers is taken into account. We will discuss this effect
in ect. 5.4.

Algorithm and Result

Select three points PI, P2, and P3 and a starting point qo arbitrarily dis-

n+I -

Iterate the equation above ad infinitum.


What pattern do the points enerate in the plane? The

variables x and y, representing the pixel coordinates on the screen.


struct{int x, int y} qn={20,20}, pw,
[3]={{10,10},{MAXX-l0,10},{MAXX!3,MAXY-l0}} j

The initial values are specified right in the type declaration. Now in each
step of the iteration one of the three points p [i] is selected by generating a
ran om num er i
pw = p

and a new point is calculated:


qn.x = (pw.x + qn.x)!2 j
qn.y = (pw.y + qn.y)!2 ;

Then a pixel is plotted at that position, e.g., on the PC via


104 3. Iterations

each other. The structure is self-similar: all triangles look the same, indepen-
dent of their size (of course, this is only true for triangles that are much larger
.. .

Start with a triangle,


remove a triangle from its center in such a way that three identical triangles
remaIn,
iterate this ad infinitum for all triangles remaining after each step.

list={{{O . O.}.{.5.N[Sqrt[3/4]]}.{1 . 0.}}}

triple[d_]:= Block[ {dl.d2.d3}.


dl={d[[1]] .(d[[2]]+d[[1]])*.5.

Fig. 3.15. Points in the plane,


generated by the game of dice

ners 0 e
are gIven y
p[1], and p[2]
3.3 Fractal Lattices 105

The command Map is used to repeatedly apply this function to the entire list

objects which are drawn by Show:


plott:= Block[ {listtvo.plotlist}.

Figure 3.16 shows the result. We obviously obtain the same structure as in
the previous game of dice, but now, we can easily convince ourselves that the
self-similar framework is a fractal in the limit of infinitely many iterations.

-_ l' In M t _ I' ( -t) In 3 + In M _ In 3


D 1m -1m --.
t~oo InL t t~oo (-t) In2 + InL In2
106 3. Iterations

xerClse

A Koch curve is defined by the following iteration: The central third of a line

Start with an equilateral triangle, and iterate the construction above as


often as possible. As a result, you will obtain the Koch snowflake.

Literature

Wein-

3.4 Neural Networks

thinking.
3.4 Neural Networks 107

tecture, as well as from its function. Such algorithms and their realizations
in hardware are called neural networks and neural computers, respectively.

,
digits, recognizing engine defects by their noises, judging the creditworthi-
ness of bank customers, predicting stock prices, etc. It turns out that neural

Physics

Here, any neuron can have just two states: it is quiescent (Si =
= 1 . The coefficients Wi E Ii model the stren

complex biochemical processes; for example, a synapse can have an inhibiting


108 3. Iterations

(So = -1).
This is the biological motivation for (3.28). Mathematically speaking, this
. .

tions, however. Geometrically speaking, Sand w = (W1, W2, .. , W N) are vec-


tors in N-dimensional space. Equation (3.28) separates the outputs So = 1
. .

shown that their number is less than 2(N ), which, for N = 10, still amounts
to 1030

scn e y neura ne wor 1S supp 1e W1 ne! er ru es nor pro-


grams, but examples. In our case, the examples consist of a set of input-
output pairs (xv,yv).with Xv = (XVl,XV2, ,XVN), Yv E {+1,-1}, and
v = 1, ... , M, provided by an unknown function. As in the case of real
nerve cells our network learns b "s na tic lasticit" Le. it adusts the
strength of its weights Wi to the examples. In the ideal case, the perceptron
can correctly classify all inputs after the learning phase:

D. Hebb had already postulated in 1949 that synapses adjust themselves to


the activities of their input and output neurons. Mathematically, this state-

(3.30)

, ,
synapses which fulfill (3.30) also fulfill (3.29) perfectly, which is the condition
to be learned (Xj E {+ 1, -I}):
N
w .X =. -Xj
N
(3.31)
3=1

This method however

x p
correctly by the current vector w:
3.4 Neural Networks 109

This is the well-known perceptron learning rule, whose convergence was math-
ematically proven in 1960 by Rosenblatt: if the M examples (xv, Yv) can be
. . .

w* . Zv > C > 0 for all v exists. The constant c > 0 corresponds to the
smallest distance of the points Zv from the hyperplane defined by w*.
i I tis ou ter
, . .,
which we have w(t) . Zv < O. For each of these, the learning rule yields
1

(w (t + 1))
2
= (w (t)) 2 + N2 w (t) . z v + N2
1
(z v )
2

N'
Note that (zv)2 = Lj Z~j = N. Iteration of (3.34) from 0 to t, using w(O) =

<-
- N'
An estimate of the scalar product w* . w(t + 1) yields
1 c
N N'
which, iterated from 0 to t, leads to

- N'
Now we insert (3.35) and (3.37) into Schwarz's inequality
(w (t))2 (W*)2 > (w (t) . W*)2 (3.38)

(3.39)
or

(3.40)
110 3. Iterations

, ,
classified correctly. Thus, the perceptron rule can actually learn all learnable
problems perfectly.

(with probability 1) for M < 2N.


After the learning phase, the perceptron can generalize. This means that

where the average is taken over many inputs S. The value 9 = 1/2 is the
result of random guesses and the perceptron can not generalize in this case.
For 9 > 1/2, on the other hand, the perceptron has recognized a certain
re ularit in the exam les learned and has a robabilit of a reein with
"
We now want to use the perceptron for the purpose of time series analysis
and make predictions for the next step. We assume we have a sequence of

F = (1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1, -1, ...) (3.42)
In each step, the perceptron probes a window of N bits,

and makes a prediction for the bit Fv+N:


FV+N = sign (w xv) . (3.44)
Then the erce tron earns the exam e Xv F v N accor in to t e Rosen-
blatt rule (3.32), shifts the window to the right by one bit, and makes a new
prediction for the input F v+N+l. This is repeated and a hit frequency 9 is
determined.

,
sequence, on the other hand, will always give a hit frequency of 9 = 50%.
3.4 Neural Networks 111

Algorithm

1. Read input:

2. Calculate the potential:


for (h=O., i=Oj i<Nj i++) h += weight[i] * neuron[i];

if (h*input > 0) correct++j


4. Learn:
if (h*in ut < 0)
for (i=Oj i<Nj i++)
weight[i] += input*neuron[i]/(float)Nj

for (i=N-1' i>O i--) neuron[i = neuron[i-1]


neuron[O] = inputj
} /* end of while */

the screen. The hit frequency in the form correct/runs* 100.0 is displayed
after each step, as are the values of the weights and the result of the predic-

e program.
The version nnf name takes the inputs 1 and 0 from the file name. At this
point, we want to show briefly how to pass arguments from the command
line and how to read a file. The function main now has arguments:

argc contains the number of words entered on the command line, in this case
ar c=2. The two arra elements ar v [0] and ar v [1] contain the addresses

corresponding file is then opened for read access.


112 3. Iterations

if (argc==1> {printf ("Input file name?");


scanf("hs". str);
}

1.
found");

The characters 1 and 0 are then read b the followin code:


while (feof (fp)==NULL)
{ switch(fgetc(fp
{ case'!': input=1; break;

Result

1010101010 ...
correct

111001110011100 ... ,
3.4 Neural Networks 113

prp.diction correct
hit pe:rcentage: 58.65%

Fig. 3.17. Neural network for


the prediction of a time series

Now we attempt to type in 1 and 0 randomly. We have tested this with


students in our class, each of whom wrote about 1000 copies of the two char-
acters to a file, kee in the se uence as random as ossible. The evaluation

A~U'~A~' ,

by hand. Frequently, just the prediction 1 --t 0 and vice versa yields a hit
frequency 9 > 50%. The perceptron recognizes such rhythms rather quickly.

We cordially invite our readers to attempt both: generating random bits and
outwitting the perceptron.

Manually write a sequence of about 2000 characters to a file name. dat,


namely 1 or 0 in as random an order as possible. Extraneous characters are

you a good random number generator? Check if random bits generated by


the computer yield a hit frequency of about 50%. How much is the deviation
from all ?
114 3. Iterations
TO
..................
Hertz J., Krogh A., Palmer R.G. (1991) Introduction to the Theory of Neu-
ral Computation. Addison-Wesley, Reading, MA
., ,
....... \ ... .,.,.." . . A~ T~+_~
1\ ,r:~ 11
......
D
, D , , T uu..
. \AU
n
.... ,
l\If 'T'
..l
..... 1100t::\
1\.T .1 "'T
...,-u .........
_AAV.~

auctlon. ~prmger, tlerun, tteiaelOerg, !~ew lorK


4. Differential Equations

ential equations. For example in Mathematica, one can use NDSolve to solve
ordinary differential equations without knowing the details of the program.

4.1 The Runge-Kutta Method

First, we want to discuss the solution of an ordinary differential equation.


n

y(n) =f(x,y,Y',Y", ... ,y(n-l) , (4.1)

,
obtains the following set of equatio~s:
116 4. Differential Equations

,
Yl = Y2
,
Y2 = Y3

,
Yn-l = Yn
,

y , ()
x l'1m Y (x + Llx) -
= ~x~o Llx
y (x) = f (x,y) (4.3)

If the vector is known at the oint x then its value after a minute ste
x + Llx can be calculated according to (4.3). This is also the essence of the
numerical method: The spatial coordinate x is discretized and an attempt is
made at calculatin at the ad'acent oint x + Llx as recisel as ossible

dimension n = 1, i.e., y and f each have just one component Y and I. The
algorithm to be presented can easily be extended to arbitrary dimensions

Y' = I (x, y) . (4.4)


To start the calculation, we obviously need an initial value y(xo) = Yo. First,
we Iscretlze t ex-axIS:
Xn = Xo +n ,
where n is an integer and h is the step size. Let Yn
. .
= y(xn ) and y~ = y'(x n ).

(4.6)

Yn+l = Yn + hi (x n , Yn) (4.7)


The error is of the order h2 This method is not recommended for practical

Yn+l/2 = Y (x n + h/2). This is the idea of the Runge-Kutta method which


4.1 The Runge-Kutta Method 117

en
2
h 1 h3)
I
Yn = Yn+l/2 - -Yn+l/2 + II
-Yn+l/2 +0 (

Yn+l = Yn+l/2 + h I
2 Yn+l/2 + (h) 2
1 II
2'Yn+l/2 +0 (
h
3) . (4.8)

(4.10)
Consequently, this second-order Runge-Kutta method yields an error of order
3

that has prevailed in practice needs four calculations to achieve an error of


order h 5 We only state the result:

k4 = hf (x n + h, Yn + k 3 ) ,
k1 k2 k3

finding an appropriate value for h is to check the result for different values.
If the change in Y is small, one can afford large step sizes, while many small

p z n wn.
To estimate the error, one calculates one Runge-Kutta step (4.11) with
a step size 2h (result Yl X2) in parallel with two steps of step size h (result
. .
118 4. Differential Equations

Y (x + 2h) = Y2xI + 2h5 </J + 0 (h 6 ) ,


5 6

since we are using a fourth-order method. The constant </J is determined by


the fifth derivative of the function y(x). For the difference L1 = YIx2 - Y2xl,
this leads to

Therefore, if we choose two step sizes hI and ho , we have


L1 0.2
0

x = v,
iJ = f (x, t) (4.15)

(4.16)
This means that the algorithm jumps back and forth between calculating the
.. . .

for h ~ OJ this is the idea behind the Richardson extrapolation and the
4.1 The Runge-Kutta Method 119

Algorithm

,
tively in this case. H J depends only on y and not on x, then (4.11) can be
written as
.=
Module [{kl, k2, k3, k4},
kl = h N[f/.Thread[y -> yp]];
k2 = h N[f/.Thread[y -> yp+kl/2]];

The function Thread assigns the corresponding value from the list yp to each
.

Yo via
RungeK[f_List,y_List,yO_List,{x_, dx_}]:=
NestList[RKSte [f, ,#,N[dx]]&,N[ O],Round[N[x/dx]]]

For comparison, we also program the Euler method:


EulerStep[f_,y_,yp_,h_]:= yp+h N[f/.Thread[y -> yp]]

Here p is the angular velocity <j; and q is the displacement angle ep of the
pendulum. As in Sect. 1.2, ener y and time are measured in units of mgl and

by
120 4. Differential Equations
r rl. __":' ... ___,
....
... ......
fl'\ rl. __ ..: , ... __ _, _1'\ 1.
;.r... ~ r._" '''' ."', '.;.''' ...~"
"'1'1'''' "t'....oAoV.t'V", ""&U"'A, ... ~

Figure 4.1 shows the result. The curve on the left is the correct result for
an initial angle <Po = 1r /2. Without friction, the energy is conserved and the
Tl'llH:!t hA 1.1.' ., , (QAA ]:;'i 0'
.
, -, ]:;'nr thA nlnt nn tho riO'ht.
v-0 -I;" I;"

shows the result of the Euler method using the same step size h = 0.1. It can
be seen that this method gives a completely wrong result, since the energy
. :mn t.hp i~ not. .
ru:
'-'.I , W'V Lo....L
..-" . , r
.1.1
.
't'lT_
'Y'V o.uu
-l-l
a.
L_ _J:L"t_J:_
II'V.L ...... V.L II.L..'V "'V",U" P'l'
to the graVItatIOnal torce and obtam a SOlutIon ot the equatIons ot motIon oy
RungeK[{p,-Sin[q]-r p},{q,p}.{phiO.pO},{tmax,dt}]

In Fig. 4.2 we see that the pendulum loses its energy and moves towards its
rest position q = p = O.

1 '\ 1.5 ~ -.........


~ -......... 7
1
"""\
,7
1

,/ \,
0.5 0.5
\
P 0 p 0 I

-v.,J
J
-v.,J
\ J J

-1

-1.5
~ ~ -1

-1.5
~ ~
-"... 'A
I n
V A ..." - ..." I
-A
n I
"
q q

Fig. 4.1. Oscillation of the pendulum in phase space q = <p,p = <p. Result of the
Runge-Kutta method (left) and solution of the same problem calculated with the
~Uler methOd ~ngfl,t}, wmcn ODvlously gives a wrong reSUlt

1 ~ ~
/
/.....-
////..- -..... ""
~,,"\..'\

11(1f~~>~\\ \
0.5

P 0

\ \ \ I\I\ \\.~ W / / J j '.11 1


) J I
1

~~
-0.5

-I

"--- .-/
. .
~. - ...... .,. .
-,. ..
.r II;' ~.~. J. 1l~ ::5i:J,1~1~_ a<:I
~~ ~~ ~ ~
",-,.J v.v A A.v
snown on tne leIt-nann ::51U~ UI
q Fig. 4.1, but with friction J-t = 0.05
4.2 The Chaotic Pendulum 121

A particle of mass m moves in a one-dimensional double-well potential and


is subject to an additional frictional force proportional to its velocity. Thus

mx = J-LX + ax - bx 3

Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Red-

ical Recipes in C: The Art of Scientific Computing. Cambridge University


Press, Cambridge, New York
the Per-

oer ., u lrsc n ro pnnger,


Berlin, Heidelberg, New York
DeVries P.L. (1994) A First Course in Computational Physics. Wiley, New
or

4.2 The Chaotic Pendulum

,
the nineteenth century, that a simple mechanical system can exhibit complex
behavior. The idea that one merely has to specify the initial conditions as

simple, externally driven pendulum.


122 4. Differential Equations

community. Only the computer made it feasible to investigate chaotic motion


in detail and - what is possibly just as important - display it graphically.
. . .

We first consider the pendulum from Sect. 1.2 and add a frictional force. In
dimensionless form, the equation of motion for the displacement angle cp(t)

rj; + rep + sin cp = 0 (4.17)


with a friction coefficient r > O. This second-order differential equation can be

w= -rw - sin cp . (4.18)

, ,
a time interval dt. Therefore, an orbit (cp(t) ,w(t)) cannot intersect itself.
It can be shown that this means that there cannot be any chaotic motion.

re axes to t e rest position cp = ,w = or r > ,pOSSi Y ter sever


oscillations or full turns. The origin of phase space is an attractor for nearly
all starting points (cp(O) ,w(O)). Eventually, all orbits spiral towards the rest
pOSition see ig. . .
The picture changes if we allow a third direction in phase space. To do
so, we drive the pendulum by a periodic torque of strength a and frequency
wo ,

cp smcp = a cos Wo

Using (J = wot we obtain


cp = w,

(J = Wo . (4.20)
endulum is now described in three-dimensional s

with frequency Wo = 1. Therefore there are, generally, three competing time


4.2 The Chaotic Pendulum 123

the Hofstadter butterfly and the Frenkel-Kontorova model, the competition


between different length or time scales leads to interesting physical phenom-

For the time interval, we take the period of the driving torque and consider
.h
WIt t = -21rj and = 0 1 2 . .. .

individual points or a c ose curve. For Wo = W D , we get a sing e point in t e


(ep,w) plane. For Wo = (P/q)WD with p and q integer and relatively prime,
one obtains q different points, and p determines the order in which the q
pomts are accesse. ,on t e ot er an, Wo IS an IrratlOn mu tIp e 0

Thus, periodic motion results in either individual points or closed curves in


the Poincare section. Such orbits can be attractors, Le., if one starts with
I

basins of attraction are possible as well.


There is a second kind of attractors, though, so-called strange attractors.

and Procaccia: We generate N points Xi on the attractor, which should have


124 4. Differential Equations

, .
the Xi. We can formally express this correlation using the step function e(x):
N

C(R) can be interpreted as the average mass of a section of the attractor,

C(R) <X RDc . (4.24)

in each square. Let Pi be the probability that a point (<p, w) of the attractor
is found in square i. Then the entropy is defined as

and the information dimension DI is obtained from

Inc .
e-tO

Now it can be shown that the following relation between the three dimensions
holds:
c
In practice the three dimensions often agree within the experimental error.

To solve the differential equation (4.20) numerically, we choose the fourth-


order Runge-Kutta method from the previous section. As we want to be able
to display the movement on the screen while the calculation is still in progress,
we use the Ian ua e C with the a ro riate ra hics environment. In our
program the strength a of the driving torque can be changed by a keystroke
during the run; also, we can switch back and forth between displaying the
continuous motion and the Poincare section.

odeint from Numerical Recipes into one's own program.


4.2 The Chaotic Pendulum 125

calculated do not represent its actual development in time. In order to observe


that correlation, one should directly use the routine rk4 from Numerical

#define float double


#include "\tc\recipes\nr.h"
" "
"
#include "\tc\recipes\odeint.c"
#include "\tc\recipes\rkqc.c"
#include "\tc\recipes\rk4.c"

you on y ave access 0 umenca eczpes . ,you s ou rep ace r qc . c


with rkqs. c and rk4. c with rkck. c. The path name has to be modified, of
course, to indicate where you have stored the programs. We have added the
first command so that all real variables in the program and in the Numerical
Reci es are of the same t e double. The routine odeint is called in the
following form:
odeint(y,n,t1,t2,eps,dt,O.,knok,knbad,derivs,rkqc)

e ill erva 1, 2 an en y IS rep ace y e resu c.p 2 ,W 2 . e


variable n denotes the number of variables. Since we replace (J by W D t again
in (4.20), there are only n = 2 variables. With eps we can specify the desired
accuracy, an t IS an es Ima e 0 e s ep SIze reqmre. n ou pu, e van-
abIes nok and nbad contain information about the number of steps needed.
The parameter derivs is the name of a function that is used to evaluate
the right-hand side of (4.20). In other words, derivs(t,y,f) calculates the
com onents of f from t and . In our exam Ie we have
Y 1] = c.p ,
y[2] =W ,

f[1] = y[2] ,
f[2] = - r * y[2]

possibly one's own, just as well.


126 4. Differential Equations

main 0
{
t

yold=y[2J/ysc*yimage/2+yimage/2;
rectangle(xold,yold,xold+l,yold+l);
t=t+3.*pi;

void derivs(double t,double *y,double *f)


{

Here, too, a good programmer should have all constants calculated in ad-

replace t + 311" by t + dt, where the time step dt should be chosen such that the
orbit progresses by only a few pixels each time step. In this case, of course,

Results

periodicity of the angle cp (=horizontal axis).


4.2 The Chaotic Pendulum 127

,
back and forth between periodic and chaotic motion.

a is 0.7

xerClse

A liquid of given viscosity 1-, heat conductivity K, and density p is enclosed


128 4. Differential Equations

forced ,endufmu :
r - 0.25 Il .. 0.100000

.--.-.-_.'
eriod 7 X 211" W .
4.2 The Chaotic Pendulum 129

I~l~f

. .;,._ .......................
"---------
fore" pendulum :
r- 025 11 .. 1.300000

of such a Benard experiment near the transition from ordered to chaotic


behavior. The model uses a Fourier expansion in the x- and z-directions and

ree equa-

x= -(1 X + a yr ,

Z=XY-bZ.
Here, X represents the velocity of the circular motion, Y the temperature

system's behavior.
This system is interesting for various applications:

in energy technology: heat conduction of insulating materials.


130 4. Differential Equations

as a Poincare section for Z = constant = 20.0.


To better determine the intersection with the plane Z = constant = 20, a
linear inter olation between the last value below 20 and the first one above

When does chaotic behavior set in? For r = 28, what is the dimension of
the strange attractor in the Poincare section mentioned above?

Literature

Cambridge University Press,

ical Recipes in C: The Art of Scientific Computing. Cambridge University


Press, Cambridge, New York

4.3 Stationary States

,
solids are concerned. In the realm of the microscopically small, only proba-
bility statements for the position and momentum of a particle are possible;
. .
ca e statIOnary c ro mger equation, an elgenv: ue equatIOn or t e energy
operator, which in the coordinate representation takes the form of a linear
differential equation. In principle, this equation can be solved numerically
USIng e me 0 s rom e prevIous sec Ions. ere IS, owever, a more e-
ficient method for numerically solving the Schrodinger equation, which we
want to illustrate using a simple example, the anharmonic oscillator. For the
Schrodinger equation we have the additional problem that the energy cannot
take all real values but onl certain discrete ones which are determined b
4.3 Stationary States 131

A quantum particle is described by a complex-valued (in general) wave func-


tion 'l/J(r, t) that obeys a second-order partial differential equation. I'l/J(r, t)1 2
. . . . .

dent of time, the wave function 'l/J obeys the stationary Schr6dinger equation,
which, in one spatial dimension, has the following form:

Since the potential V(x) is real, we can choose 'l/J as a real-valued function
too. Equation (4.28) describes, for one dimension, the stationary state of a
. . . . . . .

For symmetric potentials V(x) = V( -x), the stationary state, too, has
the symmetry 'l/J(x) 'l/J(-x), where the sign alternates with increasing

'l/J" (x) + (_x 2 - AX 4 + 2E) 'l/J (x) = 0 . (4.29)

energy E8 = 1/2, EO can only take integer nonnegative values,


EO =n ! where n =0 1 2 ... .

analytic at A = o.
132 4. Differential Equations

Several problems have to be solved: How can the eigenvalues E be found?


Which algorithm does one use to integrate the Schrodinger equation? Which

One could say that we "shoot" the wave function 1/1(x) to large x values
for different values of E until the boundary condition I1/1 (x) I ~ 0 for large x
. . .

1/1" (x) + k (x) 1/1 (x) = 0 (4.31)

n, i.e., 1/1n = 1/1(x n), 1/1~ = 1/1' (x n), and so on for the higher derivatives. From
the Taylor expansion,

... ,
we obtain

For 1/1~ we can substitute


1/1~ = - kn 1/1n , (4.34)

derivative by the second one in its discretized form:


2
~ d
2
(4) " _ d
.
(4.35)
4.3 Stationary States 133

(1 + ~~ k,,+1) !/In+l - 2(1 - 152h2kn) !/In


2

With this we can calculate the complete set of 'l/Jn values from two adjacent
initial values.

keyboard input.
The integration step (4.36) turns into the function step (&x, dx, &y , &ym1) ,

n n-l
to change the values of x, y, ym! from within step, we have to pass the ad-
dresses of these variables, each of which is marked by an &. Note that in C

e argumen s.
With this, the calculation of 'l/Jn+l goes as follows:
double step(double double dx, double *ya,

xml;

(1.+dx*dx/12.*k(xpl;
xml=x; x=xpl;
yml=y; y=ypl;

}
134 4. Differential Equations

step size dx covered by the iteration loop for (...) corresponds to exactly
one pixel of the x-axis on the screen; (xs,ys) are the screen coordinates. The

x=dx/2.; y=yml=l.; ysold=l;


for(xs=l; xs<XMAX; xb++)

ypl=step(tx,dx,ty,tyml);
ysnew=(l.-ypl)*YMAX;
if(abs(ysnew10000) break;

depending on the input, the value of e (= E), the energy step size de, or the
step size dx (= h) of the integration is changed.

The program schroedinger calculates and plots the wave function 1j;(x) for
...;i,.....~....

[6.22030088,6.22030093] .
In Sect. 2.1 we calculated the ener

submatrix and diagonalized. For N = 50, we found the value


E4 = 6.220300900006516 ,

limits by cutting the step size dx of the integration in half.


4.3 Stationary States 135

t energy elgenv ue

Exercise

Literature

er-

Springer,
136 4. Differential Equations

So far, we have only considered differential equations for functions that de-
pend on one variable (time or position). Now we want to study a wave that

Physics

(4.37)

characteristic, namely
u (x, t) = -2 sech2 (x - 4t) , (4.38)

moves to the right at a velocity v = 4, not changing its shape in the process.
Such a solution is called a soliton.

u (x, 0) = -N (N + 1) sech 2 (x) , (4.39)


results in N solitons that ro a ate at different velocities. For exam Ie for
N = 2, one finds

amplitude has overtaken a broader wave with a small amplitude. At time


4.4 Solitons 137
0 .........
\ f
~
, , I
r

-2 V
,.-..
("t)

q -4
'-"
==' Fig. 4.8. Two solitons
move away from one an-
-6 other. The numerical solu-
I .J: .J ~ .1 ..1.
"A"VAA \ ... .., ....... ';"'~ ~"I ,......A ..... " .... ~

'C'.J\.CIo'..". VU'C' \ I l.'161 Uf:-J


-8
(in:: 111 guuu "V
-10 -5 0 5 10
(t = 0.3, dx = 0.18, dt =
X 0.002)

t = 0, the two overlap to form the wave packet (4.39), whereas after their
encounter both solitons have resumed their original shapes.
We would also like to mention an interesting link to quantum mechanics:
The Schrodinlrer eauation with the Dotential V (x) = - N (N + 1) sech"~ (x)
1-. nn 7\T '-
& & ~.... ~
_1
,
~.... ,,~
.... '-'......
_1 . 1.
.,. AA.......AA
,,~.n. ~n~
'-'.LA..... ..... .......L
+1-..n. .1 . ,,~+1-.. ..... V ...nT
"AA ..... '-'.L "AA..... ... ....... ,

equation by using the methods of inverse scattering theory. Since the expla-
nation is too complicated for the scope of this book, we refer the reader to
tho ,. '" hn"t
.1"

Algorithm and Results


T.
, . .11. .1 .1. T..... .J't T . I A ll)"'" J' c. ,.
~""v"""~" "V u "v,,\'~ ".... ~ ~t.. .... " &
\ "'%.<1, YV~ ...... u.,,, ...... .,,,
tne space ana time cooramates x ana t,
u~ = u (jdx, ndt) . (4.41)
Here j and n are integers, and dx and dt are the step sizes in the x and t
cooramates respectIvely. We want to aemonstrate wnat nappens It we wnte
(4.37) too naively as a difference equation. For example, we could consistently
use the so-called forward-two-point formula for each derivative !'(Xk), i.e.,
approximate !'(Xk) by (f(Xk + h) - f(Xk))/h. For the partial derivatives this
vields
.n. .n.

au au
- --+ U~+l
1 ( .
dt - u~")
, - --+ ~
dx
(u i +I -ui ) (4.42)
at ax n n

By applying this rule three times we obtain


..q3 .. 1
'-'

- 3 --+
~

(dx)3
~ (u 3+::i _ 3u3+:.:l + 3U3n+ 1 - U3~) . (4.43)
aX n n n

With these substitutions, we solve (4.37) for U!.+l with the result
,
,; . U3+ 1 - u 3 u 3+::i - 3u3+:.:l + 3U3+ 1 - u3 "
U~+l u~ + at I ou~ t':l:':I:4)
dx (dx)3 I
138 4. Differential Equations
......
.lImS
.
~41
. .
IS ,weJ. -c
C;a0:3 U
.. , . ...
tU-;"Jj 0
.y r
..
rlIp.
~
III
r .

'J

by a list with max + 1 elements. To initialize it, we use (4.39) with N = 2:


ustart:=Table[-6 Sech[(j-max/2)dx]A2//N.{j.O.max}]

and
. ..:I.' 1.
~~rv
l'
We . the 1i~t~ I'lJ.j+k).
A V
1 1''', 1
. ,~ .
for k = 1, 2, and 3 via uplus [k] =RotateLeft [u, k] and can then formulate
the integration step {u~} --t {U~+I} as follows:
Sl;eplu_J:=\.UOlUP.lUSlKJ=n.Ol;al;eLeXl;lu.KJ.tK.;jJ'J;
u+dtl6 uluplusllJ-uJ/dx -
(uplus[3]-3 uplus[2]+3 uplus[1]-u)/dx A3

plot2 [i_ : 3] lets us plot the result after i integration steps, using dx = 0.05
........ ...:1 ...:1+ - {\ {\Il
'V.'V_
. . . .A A ~ ~v

plot2[i_:3]:= (dx=O.05; dt=O.02; upast=ustart; time=O;


Do[upres=step[upast];
upast=upres;Print[IITime lI.time=time+dt].{i}] ;
XU.l1Sl; = laD.lelt\.J-mu/:l)Qx.upreSllJJJJ'.tJ.u.maxJ'J;
L1StPlotLxu11St. PlotJo1ned->True. PlotRange->AllJJ

Figure 4.9 shows the result. After just three time steps, u(x, t) exhibits oscil-
lations, which are caused by numerical inaccuracies and "explode" after just
lIWV UIVl~
. ,. . A-
.
"."
.L lUi:), VI , Ii:) A
1
v ~A'V~
1 1
dllU l;dll ut:
1 1 1 1 1
Vll lIUt: UCLU
. .
algorIthm.
What went wrong? We have committed several errors, which we can avoid
by the following modifications:
1
.L.
TI'
.u.y a.
'1.
UJ.l' lIJ.U:;
_1. _1. l'
lI.1J.tJ
.
_1.
tJJ.J.UJ. 1..11. lIJ.J.tJ
. 1 . . ~~,
. .&_&_ -
tlOn ot a I at and a'~ I axr~ can be reduced.
2. The use of averages stabilizes the algorithm.
3. The step size dx chosen must always be large in comparison to dt.

0 ....... 1 r
~ I
~
I
0 -5
0
--
><
='
-10
Fig. 4.9. Integration us-
mg step[u] and step
sizes dx - 0.05, dt -
0.02. After just three in-
-15 tegration steps, one ob-
tains an unphysical re-
-10 -5 0 5 10 ",.. 14- 'T'l... ..l _'1. _1_,
.,
_.' --~
.1. U. A 0
n
A
U&&&'" UV ... & 0 ' -,,;v
4.4 Solitons 139

Ul = Uo
Then,
dx

1 - -I
(4.45)
2dx 6
One sees that in the second case, u~ can be calculated in such a way that
dx 2 u" cancels exactl . This reduces the error b one order in dx. In a
similar way, one can reduce the error of the higher derivatives by a suitable
choice of the coefficients. One obtains

u~' UI 2dx~-1 - U-2 + (1 (dx 2 ) (4.46)

Thus, with respect to the quality of the approximation, the algorithm used

To illustrate points 2 and 3, we want to use a simple differential equation.


In particular, we choose

with a constant velocity v. We discretize this equation in the form


uin+1 - u in- I

where we have already substituted the improved version (4.45) for a/ax.
Solving for the components (U~+l,U~+I' . ), which we combine into Un+l,
. ..

with a tridiagonal matrix M. Obviously, the solution of (4.48) is u~ = MnuJ,


from which we can see that the magnitude of the eigenvalues of M is critical
or testa I Ity 0 t e ont m. or t e el enmo es W 0 matnces 0 t IS
type we use a Fourier ansatz of the form wi = exp(ikjdx) with a wave
vector k whose possible values are determined by the boundary conditions.
If we choose an eigenmode w = Wo as our initial state, and designate the

w~ = an exp (ikjdx) . (4.49)


140 4. Differential Equations

a n + 1 _ an eikdz _ e- ikdz
n
- - - - = -va ----- (4.50)
dt 2dx

a = 1 - i ~~ sin (kdx) (4.51)

to be constant grows exponentially with time. The algorithm is unusable!


A seemingly insignificant change can stabilize the algorithm, however. In
i

uin ~ !2 (u jn+ 1 + u nj - 1
) (4.52)

This ives us
j+l _ j-l
n n

Now we have lal < 1 for

only remain stable if the time step dt is chosen so that it is smaller than
the propagation time dx/lvl. Or, from the opposite perspective, the spatial
. ..

rically as well:
j i+l _ j-l
n+ n n

vdt . kd
= - 21 dx SIn x . (4.57)

a = - I. -vdt
SIn
. kd x (4.58)

be chosen to be sufficiently small compared to dx.


4.4 Solitons 141

ax 2dx
U ~ !3 (u in+1 + uin + uin- 1 ) ,

-
8x 3
---I..
--r 2(dx)3
( 3+
Un
_ 2
Un
3+ + 2Un3- - u 3n- 2)

We call n - 1 past, n present, and n + 1 future. Then a time step is given by

lot3 i :9 :=
(Do[ufut=step2[upres.upast];
upast=upres;upres=ufut; time = time+dt. {ill;
Print [lltime II. time] ;


Plot[uu[x],{x,-10 . 10.},PlotRange->All.
Frame -> True. Axes -> None] )

is shown by the dotted curve. The wave trough u(x,O) turns into two soli-
tons that move to the right at different velocities. This becomes particularly

the large amplitude approaches the slow one. At t - 0, the two combine
to form a single wave trough, and after the encounter both resume their
142 4. Differential Equations

-0.2

10

Fig. 4.11. The same data as in


Fig. 4.10, but as a contour plot and
Wit I erent ranges In space an
time. While being passed, the small,
broad soliton is delayed, whereas the
-0.5 o large one is accelerated in the pro-
t

ure 4.12 shows the numerical solution for the initial state u(x, 0) = -4 sech2 x.
In addition to the soliton that moves to the right, additional waves disperse
4.4 Solitons 143
()

-1
....-......
'\.
"-/'
/"\
, I
f

c;) _,.
q
-5
~
-3
Fig. 4.12. Results similar
-4 L ,. . ...". ~ n ,. ~.

an
. ..
bV bUVOOlJ &U

Inn,l~
. !:i{,a{,t: '(1,\,x,
.I: .If) "%.0, UUb &VJ.
-~
U) -
-q seen' X. In aaWtlOn to
-10 -5 0 5 10
the soliton moving to the
x right, waves are radiated

icantly in the process. Obviously, the length of the lists {u~}j:O increases
as 1/dx. The following exercise is intended to demonstrate that, at the same
time the maximum dt has to be reduced in nronortion to (dx)3 for the sake
..... ~ n4- ... h;l;4-u
"' .. v

Exercises

The stability of the ale:orithm proe:rammed in step2 [u , w ] is limited sie:-


nificantly by the discretized third derivative.
1. Remove the nonlinear term from the full KdV equation, i.e., investigate
L ,_

1..l.U::: ~'i
.
~A. ~3A .
..., .... ..., ....
- -- - 8x 3 (4.59)
8t
The discretization used here yields
rlf (",j+2 ,>",j+l ..L ,>",j-l ",j-2\
u n+l
J
-- u n-l -
J \ n n n n I
. (4.60)
(dx)3
Investie:ate the stability of this ale:orithm by usine: the ansatz (4.49) in
(L1 I{O\ , , tn (L1 ~7\ thiCl lO!llrlCl tn tho ,. ,
, .~
th!llt
T"\
..... , , -J .. ~ -

.
1 2idt [sin (2kdx) - 2 sin (kdx)]
a=--
a (dx)3
.
NumerIcally determme the maxImum J.L of I sm{2kdx) - 2 sm{kdx)I {p, ~
2.6), and show that, in combination with the requirement lal < 1, this
yields the stability condition
1 ~

dt < - (dx)" . (4.61 )


p,
144 4. Differential Equations

,
mine the stability limit with respect to dt, for a given dx; i.e., approxi-
mately determine the maximum dt allowed as a function of dx. Confirm

Literature

, ,
Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Red-
wood City, CA

4.5 Time-dependent Schrodinger Equation

its motion is
,
back and forth regularly. This classical picture, which is based on the idea of
a pointlike mass with precisely defined position and momentum, no longer

that the stationary states in this case are standing waves. But what happens
to an initially localized wave packet that moves towards the walls of the box?

v w v p isperses,
and wild interference patterns arise from which smooth wave packets sud-
denly reemerge. Finally, the entire process repeats periodically with time.

Ph sics

,
which moves in one dimension in a potential V(x). Then 11/J(x, t)1 2 dx is the
4.5 Time-dependent Schrodinger Equation 145

,
coordinate representation:

In order to put this equation into a dimensionless form, we normalize the


time by to and the position by Xo:

Now we choose to and Xo such that the following equation holds:


!it = 2mx 2

tIme III umts 0

H is the normalized Hamiltonian of the particle. There are two ways to


numerically solve this equation. First, we can calculate the eigenstates and
eigenvalues of the stationary equation Htf; = Etf;, expand tf;(x, 0) in terms of
the e a h .f ri r it. w
can directly integrate the time-dependent equation as shown in the previous
section. The second method can even be used for problems for which the first
one fails which is wh we want to describe that method in the al orithm

Here, the coordinate x is expressed in units of the box's width a, and the
energy E in units of !i2/2ma 2 . The energies En of the stationary states tf;n (X)
are known from the uantum mechanics course:
n =n 1r , were
tf;n (x) = { y'2 c?s (nITx) for n odd _1 < x < ! .
(4.67)
y'2 sm (n1rx) for n even' 2 - - 2
146 4. Differential Equations

so for 1j;(x, t) we obtain


00

C2m-1 exp
m=1
00

+L C2m exp -i1r 2 (2m)2 t sin (2m1l"x) (4.68)


m=1

, ,
2
of the energies En. Each frequency W n = n 11"2 is an integer multiple of the
fundamental frequency WI = 11"2. From this it follows that 1j;(x, t) is a periodic
. .
,
entirely returns to its initial state 1j;(x, 0).
We will see in the results section that simple patterns emerge even at

1j; (x, ~) = -1j;e (x, 0) + 1/;0 (x, 0)


= -1j;e (-x, 0) -1j;0 (-x, 0) = -1j; (-x, 0) (4.70)

If we insert the result from (4.70) here, we immediately get

the complex interference patterns. The results section shows, however, that
4.5 Time-dependent Schrodinger Equation 147

a consequence of the initial condition we have chosen,


2

The function 'l/J is a Gaussian of width (J, which is concentrated near x =


-1 4, multiplied by exp(ikx). Owing to this factor, the particle has an initial

(4.74)

'l/J (x, I) = -i'l/Je (x, 0) + 'l/Jo (x, 0) . (4.75)

(4.76)

cos kx sin kx ,

i.e., a term which for (J =.0.05 is of the. order exp(-25). The remainder can

= 21 [ I'l/Je (x, 0) + 'l/Jo (x, 0)1 2+ I'l/Je (x, 0) - 'l/Jo (x, 0)1 2]

In summar we obtain

(4.78)
148 4. Differential Equations

j (x, I) '" ~j (x,O) - ~j (-x,O) , (4.79)

At even shorter times, waves with a simple structure arise as well. If we


set t = Tp/q with integers p and q which are relatively prime, the phase

, x, IS a superposItIOn 0 q waves, eac 0 w lC IS an III mte parba


sum out of that same expansion for "p(x,O). If we assume that each partial
wave is a smooth function, then their superposition is smooth as well and
"p(x, t) exhibits a simple structure at those times. This is precisely what we
will s r whe we do the numerical inte r tio .
With this we conclude the analytic considerations and turn our atten-
tion to the description of the numerical integration of the time-dependent
Schrodin er e uation.

Algorithm

First, "p(x, t) is discretized:

Here, j and n are integers, and dx and dt are the step sizes of the space and
time coordinates. As before, we write the second derivative as

with an error of the order O(dx 2 ). Now we can discretize the time deriva-
.
IV, n y
.
1 V
however, does not conserve the overall probability "p x, t dx = 1, which
is not allowed to change with time. It is indeed possible to find a discrete
approximation of the partial differential equation that conserves the over-
all robabilit. To this end the discretized time evolution 0 erator must be

The solution of the Schrodinger equation (4.65) can also be written in the
form

The approximation
e- iHdt ~ (1 - iHdt) +0 dt 2 , (4.83)
W lC correspon
hand, with
4.5 Time-dependent Schrodinger Equation 149

(4.87)

With this, (4.86) yields


.2 (dx)2 i-I _
n+l -

We have abbreviated the second line which onl contains terms referrin to
the time step n, by {}~. This equation has the form
T1/Jn+l = nn , (4.89)
with a tridia onal matri

this. We use the ansatz


"/,i+ 1 i "I,i
_
If''n+l - a If''n+l + tr1.1n . (4.90)

-1

1/J~+1 = 2
2 + (dx)2 Vi - i (dx)2 - ai 1/J~+i + ~ - {}~ (4.91)

solve for ai and ~. The result is


150 4. Differential Equations

. . iJ!.-1
~ = f}~ + ;-1 . (4.92)

lated from the wave function tP~. To solve these equations, we need the initial
state tP~ and boundary conditions. Since we want to confine the particle in a
. .. . .

where we have redefined the boundary as x = 0 and x = 1, as this is easier


to program. The number of grid points, J, is thus fixed at J = 1 + l/dx. At

2
2 (. 2 (dx) )2 1 ) 1 _ 1
tPn+l + 1 dt - (dx V - 2 tPn+l - f}n . (4.94)

(4.95)

Since the boundary value on the right, tP~+1 = 0, is fixed, this allows the
calculation of the entire vector tP~+1 at the time step n + 1.
.. .
1. Choose an initial state tPb and use it to calculate f}~ according to (4.88).
2. Calculate the vector aj from the initial value given in (4.95) and the
recursion formula (4.92) .
. For all ositions calculate the variable b!. usin the initial value from

4. Use (4.96) to calculate the values of the wave function ~+1 for the
next time step, using the initial value tP~+1 = o. This also yields {}~+1

As mentioned before, we define the initial state as a Gaussian wave packet


that moves with a mean momentum k:
4.5 Time-dependent Schrodinger Equation 151

, " n , ,
{~} are complex numbers. Whereas Mathematica, as well as other languages
like Fortran, can deal with those numbers directly, in C one has either to

typedef struct{double real, imag; } complex;

(4.98)

can be found in the function calculate_b which performs the iteration of

{
int j double a2;

b 1 .real=omega 1 .real;
b[l].imag=omega[l].imag;
for (j=2;j<J;j++)
{a2=a[j-l].real*a[j-l].real+a[j-l].imag*a[j-l].imag;
. .

(b[j-l].imag*a[j-l].real-b[j-l].real*a[j-l].imag)/a2;
}
}

00

Cn = 2 /.' sin (mrx),p (x, 0) dx . (4.101)

XQ = 0.25. As we have already seen, the wave has to return to its initial state
152 4. Differential Equations

time scale t2 ,..... 1/20 = 0.05.


Finally, the fourth time scale, which also gives us a handle on selecting
. .. .

the sine in these equations by an exponential function, the individual terms


in the sum (4.100) take the form
c
so the phase velocity v~ for this partial wave has the value
v nPh = n1r . (4.103)
To estimate u to which n the coefficients c ive si nificant contributions we
note that the Fourier transform of a Gaussian is a Gaussian again, but with
the reciprocal width. The factor exp(ikx) turns into a shift by the distance k
in Fourier s ace. From this we can derive the n-de endence of c
2

On the screen, we can only display those amplitudes which amount to at least

1 2 2
20" (n1r - k) < In (1000) => n max ~ 35, v~~x ~ 100. (4.105)

(4.106)

numerical calculation according to (4.85) yields


4.5 Time-dependent Schrodinger Equation 153

For the absolute value of the difference between these two expressions, the
Ta lor ex ansion of dives the result

(4.108)

exact time evolution as the integration time increases.

Initially, the wave does not yet notice the box. It moves to the right and
disperses in the process. As soon as part of the wave is reflected off the wall,

pattern 1. . ,e t. n t e ri t- an art 0 t e ure one can see t at


after just a short time (t = T /40) an irregular interference pattern has formed
that spans the entire box. This pattern is typical for almost all times.
Suddenly, though, regular shapes arise from the seemingly chaotic move-

and T /2. As shown before, two wave packets form at t = T /4, which move
towards and then interfere with one another (Fig. 4.14, right), and at t = T /2
154 4. Differential Equations

Fig. 4.14. The wave packet 11/J(x,t)1 2 at times t = T/12 (left) and t = T/4 (right)

Fig. 4.15. The wave packet 11/J(x,t)1 2 at times t = T/3 (left) and t =T/2 (right)

,
coordinate even more. This is because so far we have used the energy values
2 2
Ell = V 1r of the exact Hamiltonian H in our considerations regarding the

, II

and the corresponding eigenvectors cPt, which, of course, are subject to the
boundary conditions (4.93), are known as well, however:
4.5 Time-dependent Schrodinger Equation 155
156 4. Differential Equations

(4.110)

E v previously considered. This explains both the broadening and the time
delay of the wave packet in Fig. 4.17. By taking the modified energy values
. . . .

period.

Use the integration routine described in this section to calculate and display
the mean values (x), (P), and their uncertainties Llx, Llp as a function of

in its center. Try finding a numerical criterion for the tunneling time tT.
. . .

2
J
Lj=J/2 Itf;~'1
Wn = J j
2

Numerically determine the dependence of the tunneling time Vo on the


width d of the barrier.
5. Monte Carlo Simulations

.. .
IV' : II I [,f-'
,...
"al'
. ---t
.
---t l"U Ule L Le ---t

...., ..
~Ul::; 1::; Lue

of associations which gave an important method of computer simulation its
name. With the help of random numbers, one can use the computer to simu-
late, for example, the motion of an interacting many-body system in a heat
reserVOIr. As m the real experIment the temperature and other parameters
can be varied. The materials being modeled can be heated up or cooled down,
and at sufficiently low temperatures one can observe how gases liquefy, how
atoms in a magnetic material get aligned, or how metals lose their electric
r
. nr.p..
u. .4- 4-
.L.L'V.L'V
. .,n'V
, 4-
......L.LlJ
.,. 1..
lJV UO'V
~, ., .
lJV OlJUUJ ....v , y
.
-.L ~ r&&J~&~~
&

phenomena can be described with the help of random numbers. Some of these
models even have universal properties: The values of the critical exponents
+l. .... +
U&&.... u
-, :h", +l.", ,,; .........,.,
U&&~
..
."u,,~~
.... + .....l. n " " ,
.... u & U-L
.. n_",
....-L ~
+l.",
u .... ~
n .... ...,.",
~ ...... A&~
~"' ..
-L'U''' J
..............
~

"~
_. A

mrrerent moaels ana are even measurea in real materIals. ~ nererore computer
simulation is a particularly important tool for understanding the cooperative
properties of interacting particles.

5.1 Random Numbers


A computer cannot generate random numbers. It works according to a well-
., . to rll1p.~ , '.' ~.rp. ,. , to .
.. rI~.t.~.
..J ,f'. .J
.. i .P. ~ .. .. ~

and generate output data. Therefore a computer acts like a deterministic


function that leaves no room for chance. Still, there are algorithms that gen-
p.r~.t.p. "
., , Tn Tn~.nv
. . ., tp~t~ ~l1rh~.
.. , .J - .J ,"
. ., .-
, . ,
of
.,.J ~- "

.l~a.UD lIV lIV lI.l.lVD~ \'V~ ~~&_ 5~lI J.J.V.l.l.l J.

tnat tUInll tne matnematlcal dettmtlon ot "randomness. we want to oneny


introduce such algorithms here.

Ale:orithm and Results


In a computer, numbers are represented by a sequence of bits (0 or 1). If,
for example, 32 bits per number are available, a maximum of 232 different
numoers can oe represented wltn tnese OltS. Lionsequently, a tunctIOn J actmg
on these numbers
158 5. Monte Carlo Simulations

If the sequence of numbers generated by the computer passes many tests for
randomness, it is called a sequence of random numbers.

Tn = (a Tn-l + C) mod m . (5.2)


If one calls the random number generators provided by the system, e.g.,
rand in or Random m at ematica, t ese so..c e mear con ruentl
generators are almost always used. The result of the modulo function (=
remainder when dividing by m) is limited to at most m different values;
therefore, the maximum period is m. For some values of the parameters a and

the parameters (m, a, c) are given in Numerical Recipes, e.g., m = 6075,


a = 106, and c = 1283. We have used this generator to generate points on

(5.3)

c = 1283
m = 6075
rndm[r_] = Mod[a r+c,uU

The following command turns the vectors en into graphics objects and dis-
plays them on the screen:
5.1 Random Numbers 159

,
have to cover this segment of the surface evenly, except for a geometry factor
resulting from the projection of the cube onto the sphere. Instead, one can

Shov[Graphics3D[Map[Point, triple]],
. . J J

It is obvious that a total of 14 planes is sufficient to take up all points. Still,


this value has to be considered a relatively good result, since it has to be
1/3 _
160 5. Monte Carlo Simulations

There are various tricks one can use to obtain the longest possible peri-
ods and good random numbers. One can nest several different generators or
use different types of functions f. Also, one can generate bit sequences by

generates a new bit, after which the sequence is shifted by one position for
the next operation. It is known, though, that such shift register generators

and Zaman found a class of simple functions that yield almost the maximum
period. They call these functions subtract-with-borrow generators:

, n n - n-s - n-t - n-l


is positive, and to Cn = 0 otherwise. The first C value needed can be set to 0
5.1 Random Numbers 161

. 1~ '" T T. ~fO, - ~_ ,. 1 , .. " l'.


U i:uu5..... l.L VJ.U lJUcuJ. J , lJUC ,i:l _'" LJ

values of s, t, and m for which the period can be calculated. For example,
the generator
r~ = (r. ,~- r . .-:1 - r.~1) mon (2 32 - lR) (fiji)
" ,
3 2 95
has a period (m -m )/3 == 2 Moreover, this generator is excellently suited
for the language C. In modern computers, the operation modulo 232 is auto-
'" A ~. _

matlCauy DUUt IntO tne arunmetlCS or J.l:-Dlt Integers. ;::'Ince \.. auows unslgnea
integers (unsie:ned lone: int). (5.6) can be orogrammed very easily.
Marsaglia and Zaman combine this generator with
Tn = (69 069 T n -l + 1013904243) mod 232 , (5.7)

'" ~"'" , -"


a C program which calculates the average of N(= 1000000) of the resulting
pseudo-random numbers:
#define N 1000000
tvpedef unsiJlned lonJl int un1onJl;
un10ng x=521288629, y=362436069, z=16163801,
c=1, n=1131199209;
1\
r .;~ "
1. ..... "'J
if (y>x+c) {s=y-(x+c); c=O;}
else {s=y-(x+c)-18; c=1;}
x=y; y=z; z=s; n=69069*n+1013904243;
return (z+n);
}

maine)
{
...:a~ .. l.'~
,
- _.,
_-1\

.&o"'"fJ .&oJ
for (i=O;i<N; i++)
r+=mzran()/4294967296.;
printf (Il r = 7.1f \n",r/(doub1e)N);
}

x, y, z, and n are set to initial values which the user can change arbitrarily.
The auxiliary bit c has to be set to c = Y > z, i.e., in C to 1 (true) or 0
(false). Since this program was written for a computer that performs the
operation modulo 2.1~ automatically. mod(2;:S~ - 18) reduces to subtracting
18 from the difference (T n-2 - T n-3 - en-d. Of course, this only happens if
this difference is negative, as the modulo operation does not occur otherwise.
The next random number is the sum of the two generators (5.6) and (5.7).
no thp' nf -'- hun ::ITP thp
1 ,1 f".1 .~ .J ". ......1 fO .1. ,1' '.".1 '" 1 1 .1
<J V.L lJUC ..... J.., lJUC ,J;" V.L lJUC lJWU UJ.UJ. v J.uuaJ. ..... ,
127
about 2 . Therefore, this generator can run for about 1024 years. Since, in
162 5. Monte Carlo Simulations

gen-

If possible, one should look for a similar problem that can be solved exactly
and compare the numerical results to the exact ones. This provides a certain

numbers must not be neglected.


The examples in our textbook are only intended as demonstrations, not

1. Program the two random number generators


(1) r n = (r n-2 - rn-s) mod 10 ,

where we set Cn = 1 or Cn = 0 if (r n-2 - r n-5 - Cn-I) < 0 or > 0


respectively. Both generators produce integers 0,1, ... ,9 and repeat the
se uence if the last five numbers have a eared before in the same order.

105 steps.
Start with different sets of five initial digits and calculate the actual

(J' -
5.2 Fractal Aggregates 163

Verify the agreement for N = 10, 100, and 1000.

Literature

Binder K., Heermann D.W. (1992) Monte Carlo Simulation in Statistical


Physics: An Introduction. Springer, Berlin, Heidelberg, New York
Gould H. Tobochnik J. 1996 An Introduction to Com uter Simulation
Methods: Applications to Physical Systems. Addison-Wesley, Reading,
MA
Knuth D.E. 1997 II and III.

.,
Number Generators. Computers in Physics 8:117
Press W.H., Teukolsky S.A., Vetterling W.T., Flannery B.P. (1992) Numer-

In Sect. 3.3 we have constructed objects that are more than a line but less
than an area. These objects are characterized by a fractional dimension and

of chance and regularity. If particles diffuse towards a nucleus and attach to


it, the result is a loose grainy structure with a fractional dimension between
164 5. Monte Carlo Simulations

In the following, we describe a model of a growth process, in which the


undirected diffusion of particles before their attachment plays the decisive

mathematical theory for the diffusion problem, i.e., the random motion of a
particle. We want to briefly elaborate on a few statements and results which

- imensiona cu IC attIce.
vectors connecting a lattice site to its 2d nearest neighbors by L1xi, i =
1,2, ... ,2d. The motion of our random walker, which is at the lattice site
x at time t, IS etermme y teo owmg InstructIOns: ran om y se ect one
of the nearest neighbor sites x + L1Xi and jump there during the next time
step L1t. If we now put many particles onto the lattice, all of which jump
according to these same random rules, and designate the fraction that will

1 2d
U (x, t + L1t) - u (x, t) = 2d L (u (x + L1xi, t) - u (x, t)) (5.8)
i=l

(5.9)

The first is the solution of an initial-value problem which contains information


about the manner in which a random walk spreads out on average and the

ImenslOn
5.2 Fractal Aggregates 165

which means that the average size of the random path increases as Jt - to.

e space III w IC e ran m mIn


The model of Witten and Sander describes a diffusion limited growth
process which proceeds according to the following rules. One starts with
a minimal cluster, usually a single particle at the origin of the coordinate
s stem. Then another article starts diffusin freel at a reat distance and
at a randomly selected direction, until it hits the nucleus at the origin and
attaches to it. Then the next particle starts far out, again at a randomly
selected direction and so on. When avera ed over man realizations of this

,
Rmax(t) and determine its fractal dimension D from the relationship between
Rmax(t) and its mass M(t) which is given by the number of particles attached

M oc R~ax. (5.12)

not commit an error in the following dimensional consideration if we replace


R c by R max Moreover, we can assume that the time that characterizes the
166 5. Monte Carlo Simulations

1 a d-l a (5.13)
L1u = r d - 1 ar r ar u = 0 ,

u(r) = UQ (5.14)

,
ponent of the current density, ir = -'T/au/ar, is proportional to R1'n-;;'/r d - 1
By integrating this over the surface we obtain the result that the total parti-
d-2

equation:

d-l<D<d (5.16)
numerical simulations.

Algorithm

number of particles in the aggregate.


5.2 Fractal Aggregates 167

max,
the introduction of an annihilation circle skews the properties of the aggre-
gate, as it neglects the fact that the diffusing particle can get back to the

ticle is put on the start circle

circle. This leads to the following algorithm:


1. Start with an empty square lattice and position a particle on the central
attlce site.
2. Let the actual size of the aggregate be defined by the radius R max Place
a particle on a randomly selected site at a distance Rs ;::: R max from the
origin and let it jump to a randomly selected adjacent site.

max
Rs ;::: R max from the origin - the actual distance is denoted by R - it
168 5. Monte Carlo Simulations

4.

Figure 5.4 is intended to clarify this algorithm once more. For a fast simu-
lation of the DLA cluster, we use the programming language C. The square
. .

is a cluster particle at the site with the coordinates rx and ry, whereas the
sites with xf=O are available for diffusion. For very large aggregates it would
certainly make sense not to store the entire lattice, only the aggregate and
boundar sites but to avoid the bookkee in that would be necessar in this
case, we choose the easier way.

The start site on the circle of radius Rs is selected by the function


occu
void occupy 0
{
double phi;

ry=rs*cos(phi);
}
5.2 Fractal Aggregates 169
...:11 1\
~ .., ........ J 06&&&1" "
l-

int r;
r=random(4);
switch(r)
{
case 0: rx+=1;break;
case 1: rx+=-1;break;
case 2: ry+=1;break;
,.. ......... ':t ....... ~ __ 1.
'J . . ..
'

"-
oJ
.,
J

After each jump, the program has to check whether the particle is annihilated
(R > Rk). whether it has reached a site adjacent to the aggregate. or whether
!ll ClhArt
. (fl ./
\'
fl ,\
U/
Ar !ll lAnl1" " ,1 . " (J:/
\.
'> fl.\
U/
-'I tA h.o
~~- '0 u

performed in the next step. These four "ifs" in step 3 of the algorithm above
are tested by the function check () :
char checkO
.f
double rtxty;
x=rx;
y=ry;
,~ . -, t
.. J .
,

... - ..'1..... ,A'"A' "J'


._, ~~. ,
LL \.L~ , A t ... "" ........ u

if (r >= rd) return 'c';


if (xf[rx + 1 + lmax/2][ry + lmax/2] +
xf[rx - 1 + lmax/2][ry + lmax/2] +
xf[rx + lmax/2][ry + 1 + lmax/2] +
xf[rx + lmax/2] [rv - 1 + Imax/2] > 0)
return ' a' ;
else
return t j , ;
."-
Imax is the size of the drawing window. The following function adds the
particle to the aggregate:
void aggregate 0
{
double xty;
xf[rx+lmax/2] [ry+lmax/2] =1;
x=rx;y=ry;
.\ \ .
- ............,I-
, ............... t "'1'"...... I., ...r '... .1 .1" t .,
.~, ~ In ... .., .. , _ ...
.L'" ___. .OJ. I ~t' ... .LD"'" \ " It;:) "Ut""'" t J
circle(4*rx+340 t 4*ry+240 t 2);
}

J:lor the cIrcle jump, a random vector of lenKth 1t -lts IS added to the posItIOn
_1
of t.hp ~
170 5. Monte Carlo Simulations

double r,x,y,phi;
phi=(double)rand()/RAND_MAX*2.*pi;
x=rx; y=ry; r=sqrt(x*x+y*y);
rx+=(r-rs)*sin( hi);
ry+=(r-rs)*cos(phi);
}

if(kbhit( stop=1;
svitch (check 0 )
{
case
case ;break;
case
case
}

Result

square lattice
5.3 Percolation 171

Additionally the simulations show that, thanks to the introduction of the


long jumps for R > Rd, the processing time does not increase significantly if

Exercises

complete yet. While the "arms" of the cluster continue to form, additional
particles can still reach its interior regions. By arbitrarily stopping the sim-

Varying the model parameters. It is interesting to observe in which way


the form and fractal dimension of the cluster chan e if the ori inal DLA

Introduce an additional parameter Pstick into the program dla. C, which


represents the probability that a particle which arrives at a site adjacent to

Literature

MA
Sander E., Sander L.M., Ziff R.M. (1994) Fractals and Fractal Correlations.

5.3 Percolation
,
case we can use Fourier transformations to describe the periodic structures as
172 5. Monte Carlo Simulations

,
to understand materials with irregular structures as well.
There is a model for disordered materials, which permits a rather sim-

the A atoms are magnetic, with a short-range magnetic interaction which


is only effective if two A atoms are located next to one another. If there

clusters of A atoms will increase as well until, starting at a threshold value


Pc, a cluster extends through the entire crystal. The value Pc is called the

two opposite sides exists.


5.3 Percolation 173

.
1 V, U Pc or 1 eren
0
.
lattice structures and cluster definitions? How does the average size of the
finite clusters increase as P is increased up to the threshold Pc? How does the

o custer sizes look like. Does the in nite cluster have a structure at Pc?
The governing laws in the vicinity of the percolation threshold Pc are
particularly interesting. For example, we define an average size R(s) of a
custer conslstm 0 s artic es

(5.17)

e average SIze

8<00

, 8<00

At the percolation threshold ~ diverges, and close to Pc we have


v
~ '" Ip - Pcl- . (5.19)

universal exponent {3:


p (p) '" (p - Pct (5.20)

steep y near Pc.


While the density of the infinite cluster vanishes right at the percolation
threshold, P(Pc) . Pc = 0, it does exist there and has an interesting structure:
1 IS a rac a . we conSl er a square sec lOn 0 e a Ice WI Sl es 0 eng
L and designate the number of particles in this section that belong to the
infinite cluster by M (L ), then at Pc we obtain
D

the cluster increases as a power of the length, and according to Sect. 3.3 D
174 5. Monte Carlo Simulations

a e cn I perc i n u r i i ni y more compac an e


aggregate from the previous section, which was generated by diffusion.
So far, we have learned about three universal critical exponents II, f3,

a square with sides of length L. For each value of L, one obtains the number
M as a function of Pi this results in a whole set of curves. Scaling theory then

,
quantities M and L can be expressed by powers of either P- Pc or the variable
e e,
defined in (5.19). In doing so, L is measured in units of and M in units

5.22)

where f is a function which is not known initially and x is a critical exponent.


we set ,WIt a constant ,t en x = 0 ows rom us,
e
L is measured in units of and M in units of eD, hence the name '''scaling
theory."
Further, from L = ke it follows that

Ld
where Ld is the number of lattice sites in the d-dimensional cube with edges
d

(5.24)

(P - PclJ ,..., (p - Pc)-II(D-d) (5.25)


From this, one can conclude

,
tides. In finite systems, however, there is no phase transition, no sharply
5.3 Percolation 175

where f(x) = J(x 1 / V ). Consequently, the concentration P and the system size
L are related to one another close to the critical point p = Pc, L = 00.
The fractal dimension D is alread obtainable from 5.21 since for L
~ the finite system looks just like the infinite one. Therefore, (5.21) yields
M (Pc, L) tv L D . Thus one can numerically calculate the fractal dimension
D from the increase of the number M L of articles in the ercolation
?
,
ity 7r(p, L) of finding a cluster connecting two opposite faces, which therefore
percolates, in a sample of size L. Obviously,

(5.29)

that diverges for L ~ 00 and moves towards the percolation threshold Pc of


the infinite lattice. Because of the large statistical fluctuations, the maximum
176 5. Monte Carlo Simulations

With the substitution z = (p - Pc)L 1 / V and with f(dtr/dp)dp = tr(l,L)-


11"(0, L) = 1, this leads to

If we determine the value Pc(L) for as many systems of size L as possible,


uTh,'r'h

(5.33)

(5.34)
This means that the parameter v can be obtained directly from the standard

,
sites of a lattice are populated with a probability p, but the bonds between
adjacent sites. Such systems have a different percolation threshold, but they
. .

Algorithm

On a lattice

and use uniformly distributed random numbers r E [0,1]. With this, the
algorithm becomes:

3. If r < p, plot a point at the position (i,j).


5.3 Percolation 177

double p = 0.59275;
int i, j, L = 500, prj
pr = p*RAND_MAX;
. .
I I

if (rand() < pr) putpixel(i,j,WHlTE);

Figure 5.6 shows the result. One can see a pattern without any apparent

of the percolation structure, however, is not as easy to program as its gen-


eration. For example, we cannot easily answer the question of whether the

conflicts are easily resolved at the end. The details of this algorithm are well
described in the textbooks by Stauffer/ Aharony and Gould/Tobochnik.
178 5. Monte Carlo Simulations

and 1 - p respectively. This process is iterated, converting for each occupied


site the adjacent undefined sites to either free or occupied ones. When no un-

site if r < p. Otherwise, label the site as "vacant."


4. Iterate 2 and 3 until no undefined sites adjacent to the cluster are left.

observe the growing cluster on the screen, we have written the algorithm in
C. First, we label the three different cases with the numbers 0, 1, and 2:
#define NOTDEFINED 0
#define OCCUPIED 1
#define VACANT 2

This list, which initially contains only the four sites next to the center, is
processed sequentially and receives new entries while this is taking place.
5.3 Percolation 179

=0 . i <T. . i ++)
f nr ( i
rn1r-i1= r.. 1rn1= r....1__r,. _11 =
-~-'-_.-

array [L-1] [i]=VACANT;


-~-,._-- -~_

--
for(i=1;i<L-1;i++)
for(j=1;j<L-1;j++)
array L1J LJJ =NI IIIJI... ~NJ:.U;
arrayLL/2JLL/2J=U\.... UI"~J:;U;
list[O].x=L/2+1; list[O].y=L/2;
list[1].x=L/2 ; list [1] . y=L/2+1;
list[2l.x=L/2-1 list[2l.v=L/2
list r31 ,y=L /2 . 1 i st r31 ,v=T.l2-t w

=~.
putpixel(L/2, L/2, WHITE);

Here, count is a pure counting variable, whose value is incremented by 1


each time a new undefined boundary sIte ot the cluster IS generated. The
main loop, item 4 above, is:
while(! done )
-_._--",.
I
,\
- ,. u,
_" '0_ "'_
.LU.L , ....
''', .....
" ,
'\

{
i=list[ky'PD].x; j=list[ky'PD].y;
definition(i,j) ;
". /* for */
} /* while */

Thus, the program loops through L and processes the list of still-undefined
, 1. .J ~:4-~~ 'T'l..~ ,. . ..:I _.I: .: _ .: .. .: __ ( .: .: \ l.... .1- ., .
'J U&uvu. .&. &&v ............ .&.......&. .. .&."'..... ,.&.'J' UU'-N.UU aJJ .....
wnetner tne sIte \.1., J) IS aueaay aennea. TlllS IS necessary oecause tne same
boundary site may appear in the list more than once. If the site is not yet
defined, step 3 is executed, and the site (i, j) is occupied if the random
number r is smaller than the concentration p. If this newly occupied site has
any undefined neie.:hbors. their Dositions are entered in the list above. and
the value of the variable count is increased accordingly.
In the program, this looks as follows:
V01Q Qe:r1n1,&10n\1n'& 1, 1n'& Jl
1.
double r;
if ( array [i] [j] != NOTDEFINED ) return;
r = randO / (double) RAND_MAX;
if( r < .n )
I
array [i] [j] = OCCUPIED;
putpixel (i, j, WHITE);
if( array[i] [j+1]==NOTDEFINED ) ,
.~. .~
'\.COunll TT ;.L1Sll Lcounll,.ruJ . X=1; .L1SlI Lcounll,.ruJ . y=jT.L; r
, P P

1;[ \ array L1J LJ -lJ == c~NJ:;U )


1.count++;11stLcount7.PDJ.x=i;11stlcount7.PDJ.y=J-l;}
if( array [i+1] [j]==NOTDEFINED )
180 5. Monte Carlo Simulations

{count++;list[count%PD].x=i-1;list[county'PD].y=j;}
}
else array[i][j] = VACANT;
}

The program still needs to be supplied with the declarations, the graphics
initialization, and the input handling routine event () .

To begin, we use the first algorithm for the generation of the entire perco-

The concentration p and the lattice size are the same as those in Fig. 5.6. Now
one sees a percolating cluster, which exhibits structures on all length scales,
5.4 Polymer Chains 181

c
are generated almost exclusively.

xercise

Let 8 be the number of particles in a percolating cluster. In the infinitely


large system, the average cluster mass (8) of the finite clusters diverges near
the ercolation threshold cc .
(8) I"V Ip - Pcl-
Calculate the mean value (8) for all numerically generated clusters that do

Literature

MA
Stauffer D., Aharony A. (1994) Introduction to Percolation Theory. Taylor

5.4 Polymer Chains

medicine. But physics, too, has long been interested in general mathematical
laws concerning the properties of polymers. Even a single molecule which is

thousands of monomers, one must attempt to model the essential proper-


ties and structures as simply as possible. One proven model for this is the
randomly generated path, which is called the random walk in scientific litera-
ture. T e ath consists 0 man short line se ents that are .oine to ether
in random directions.
In Sect. 3.3 we have already established that a random walk can be re-
arded as a model of a pol mer molecule all of whose confi urations are

very well developed. This model neglects an important mechanism, however:


182 5. Monte Carlo Simulations

proximate analytical calculations for SAWs, simulating them on a computer


is relatively easy.

Physics

A random walk is most easily defined on a lattice. Since we are only interested

,
a random walk with continuous step sizes and directions or one on a lattice.
In Sect. 3.3 we have shown that an unrestricted random walk describes a

Here (...) is an average over all random walks and a is the length of the
individual chain links. If we define a mean length by L = V(R'iv), we obtain
D

with the dimension D = 2. This result is valid not only in the plane, but in
all spatial dimensions.
Now we consider random walks which rna

average as the unrestricted random walk; the mean end-to-end distance L


will be larger. This means that the structure of the corresponding polymer
. . .

D=-- (5.37)
3
Subsequent investigations have shown that this formula is exact in d = 1,
2 and 4 s atial dimensions an that t e numeric resu ts or ie a
value for D which is only slightly higher. In d = 4 spatial dimensions, the
value D = 2 agrees with the one from the random walk, indicating that,
in this case, the rohibition of self-intersection is no longer relevant for the

,
by mean-field theory starting with an upper critical dimension d = 4.
5.4 Polymer Chains 183

Algorithm

Consider a growing chain and let Zi be the number of sites next to its head
that have not been visited yet. Then l/Zi is the probability that a monomer
. . .

(5.38)

, ,
are assigned a high probability. This cannot be, however, since each allowed
configuration must occur with the same probability in the correct statistical

ut Imme late pOInts out a wa to correct t IS unwante pre er-


ence for compact chains. One has to assign the statistical weight Zi to each
link and weight the properties of the polymer by this amount. This way each
chain gets the same statistical weight

WN' II Zi = 1, (5.39)
i=l

an consequen IS
simulation is
184 5. Monte Carlo Simulations

(5.40)

There is, however, an efficient method to directly generate polymer config-


urations with a constant probability. While the previous algorithm lets chains

and that we can consequently talk about the first monomer unit, the second,
the third, etc.

the first monomer might point to the north, west, south, or east.
If we ignore the direction of the first chain link, then the unique charac-

step a ter t erst one IS to tee ,strrog t a e ,or to t e rIg t, an cor-


respondingly for all subsequent steps. Ergo we can describe a configuration
of a polymer consisting of N monomers by specifying a sequence of N - 1
directions whose possible values are left, straight, or right. In this context, it

have already mentioned above, the polymer chain needs an orientation. To


this end, we label its two ends as head and tail respectively and define, for
1 th t the orientation is to be s ecified from the tail end to the head.

e ements goes

1. uration on the lattice labelin the ends of the chain

... ",-,.u~vv

sites adjacent to the head (three possibilities on the square lattice).


5.4 Polymer Chains 185

sibly result from the starting configuration, with the same probability. To
do this, we label the different reachable states with l = 1,2,3, ... ,N and

L1Pl = Pl(t + 1) - Pl(t) = L [W (k -+l)Pk - W (l-+ k)p,] . (5.41)


k=l

k=l

W(k -+l)Wk = W(l-+ k)Wl (5.43)

equation.
In our case, however, detailed balance is not valid, as is illustrated by the

the probability or this new state to return to t e stralg t one IS zero.


Instead of detailed balance, we can use the following relation for the rep-
tation algorithm:

tail end and add one at the head instead, then the inverse process, removing
186 5. Monte Carlo Simulations

or not equal to zero. But if they are not equal to zero, they are both 1/3, as
the addition of a new head monomer in a specific direction always happens

of course, on the question asked. If we use the reptation algorithm to calculate


the average end-to-end distance, we expect a value that is slightly too large

e want to Vlsua lze t e SIt ermg po ymer on t e computer screen. 0


do so, we program the reptation algorithm on the square lattice in C. First,
we declare the variable type vector, which defines structures with the spatial
coor Ina es x, Y .
typedef struct { float x,Yj} vectorj
vector direction[3], polymer[NMAX]j

, ,
monomer. We start by defining the straight configuration for the polymer
and then plot it by using the function circle:

omacompe ey
5.4 Polymer Chains 187

polymer[i].x=i-N!2j
polymer[i].y=Oj
circle(polymer[i])j

Any other equiva~ent initial configuration is possible just as well. The labels
head and tail are initially assigned to the positions (N -1) and 0 respectively,

while ( !done)
{

{ head=tailj incr=-incrj
tail= (head+incr+N) Y.Nj
}
else accept c j
}

Rather than moving the polymer around in its memory location we use indices

e number N is added efore t e mo u 0 operation .


As in all our C programs, the function event () intercepts keyboard or
mouse actions by the user and returns done=! if appropriate, which termi-
nates t e while 00
The function choiceO returns an (x, y) vector pointing from the head to
one of the three adjacent sites. First the three possible directions are gener-
ated by calculating the difference (r(head) - r(neck)) - called direction [0]

, , ,
direction [2] contain the vectors (1,0) and (-1,0) respectively. Finally, us-
ing a uniformly distributed random number from the interval [0,3), truncated
. . . .
vector choice 0
{

. x;
Y j
188 5. Monte Carlo Simulations
.....
..
r .. , _ ......
.~ .... ,
r.''''
L"J A - , .. .l.U.ll L.LJ A,

direction[2].y=-direction[l].y;
r=random(3);
return direction[r];
}

The function intersection(c) returns the value 1 or 0 respectively, depend-


ing on whether the selected site is already occupied by the chain or not.
.-'.:_-(,
._, -,
int i;
for(i=O;i<N;i++)
if(c.x+polymer[head].x==polymer[i].x &&
c.y+polymer[headJ.y==polymerLiJ.y &&
i != tail) return 1;
return 0;
}

~~ V&& .... ~ .... &U && . . . . . . . . . . . . . . ~&~.t', V&&.... U & v .... &U .... ~ V&...... && . . . . . . & ...... ~"" ~&&"" V&& ....

ft. ' . ~. .
are oy l;ne v(Wut:; ~ncr. un l;ne , l;ne . . al; l;ne lOcal;lon u ....& ....

of the tail is painted over with the background color and a new circle for the
head is added. The result is a serpentine motion on the lattice. All this is
ft.. ft

void accept (vector c)


{
int hpj
void shift 0 ;
setcolor(BLACK):
circle(polymer[tail]);
hp=(head+incr+N)YoN;
polymer[hp].x=c.x+polymer[head].x;
__, __ rl._1 .,-_ .,...__ ,
.~ __ rl. __ ...:11 .,. .~

~ .... ... or" oJ oJ.. .. oJ ,


&0 _ _ - 'or'
tail=(head+incr+N)YoN;
setcolor(WHlTE);
circle(polymer[head]);
if(abs(polymer[head].x2*N I I
abs (polvrner [head] . v) >2*N) shift 0
}

To calculate the average end-to-end distance L, we have to take into account


1 1 ,1 r. 1 no I ,. .1\ I , ' J\ r.. .1 _1 .J"

each reversal ot dIrectIOn, add all lengths, and tinally dIvIde by the number
of reptation steps. In addition, we have defined a function shift 0, which
shifts the polymer to the center of the lattice whenever it is about to leave
the wmdow.
5.4 Polymer Chains 189

Running our C program generates the polymer on the screen (Fig. 5.9). At
the same time, the average end-to-end distance is printed, relative to the

n,_~I_~!lU1Ill>ui.f~~
po. liO.

Fig. 5.9. Polymer chains of length N = 50 (left) and N = 100 (right) on the square
lattice

Exercise

taking into account the number Zi of sites available in each step, as specified
in (5.39) and (5.40). Compare this implementation to the reptation algorithm

Literature

Binder K., Heermann D.W. (1992) Monte Carlo Simulation in Statistical


Ph sics: An Introduction. S rin er Berlin Heidelber New York
Gould H., Tobochnik J. (1996) An Introduction to Computer Simulation
Methods: Applications to Physical Systems. Addison-Wesley, Reading,
MA
190 5. Monte Carlo Simulations

If very many particles interact with each other, qualitatively new properties
can be the result. For example, at low temperature or high pressure gases
. .. .. . .

s stems.
Is it possible to simulate thermal equilibrium and slowly cool down a
system on the computer? Can the simulation of finite systems describe phase
transitions? In this section, we want to investigate these kinds of questions,

This model has universal critical properties at the phase transition, which are
also found for many other models and measured in real materials. We let the

Physics

Z is the sum over all possible multiparticle states S, and each state is weighted

We want to describe the Ising model, a simple model for a magnetic sys-
tem. To this end, we consider a square lattice whose lattice sites are occupied

H = -J L SiSj - h L Si . (5.46)
(i,j)nn i

in which every spin that is parallel to the field has the energy -h < O.
5.5 The Ising Ferromagnet 191

w 0 mp I u In om u r. w v
one hundred hours of processing time available on a machine which needs
about 10- 6 s for each step of the calculation. This assumes that we have

according to (5.46), which takes 2N computation steps. This leads to


2N2 N = 3.6 . lOll (5.47)

supercomputers, we can only calculate a tiny magnet of size 3 x 3 x 3, whereas


we want to describe a real material with 107 x 107 X 107 spins!

want to observe phase transitions.


One could now get the idea to just take a few randomly generated states
8 = (81 ,82 ,83 , , 8N) into account when calculating the partition function
5.45 . But this does not work because accordin to the central limit theo-
rem, randomly generated states have an energy H ~ 0 + O( VN) for large N.
The physically important states, however, have an energy of the order O(N),
which means that the are not enerated at all with the method above.

,
configuration 8(t = 0) and generates from it a sequence 8(1), 8(2), ... , 8(t)
which relaxes into thermal equilibrium. To this end, a transition probability
, .

(5.48)

P (8) = ~e-H(~)/kBT (5.49)

obeys (5.48) and is easily programmable. In principle, (5.48) still leaves us


192 5. Monte Carlo Simulations

In the limit to --? 00, tl --? 00, this time average agrees with the statistical
avera e
(A) = LP(8)A(8) (5.51)
.

, 0
librium from its potentially unphysical initial state 8(0), and tt must be so
large that the statistical fluctuations of (A)to,ft are small. Both requirements
. .
ues:
(5.52)

by (5.48), we want to briefly discuss the properties of the Ising ferromagnet


and their dependence on the system size N. The infinite system (N --? 00) in
.. .

Af can be positive or negative; the system selects one direction through ran-
dom fluctuations while coolin down. Since for h = 0 the ener is s mmetric

the phase transition.


5.5 The Ising Ferromagnet 193

for T > Te . As in the case of percolation, see Sect. 5.3, there is a diverging
correlation length e(T) which is defined by the decay of the spin correlations

(5.54)

intricate theory of the renormalization group from the seventies (Nobel prize
for K.G. Wilson in 1982). The two-dimensional model (for h = 0) was solved
in 1944 b Onsa er. Conse uentl the universal uantities are known exactI

T.e -- !- 2 2 269 J
~. kB '
kB In v2 + 1
(. fi\ )

The specific heat C diverges as In IT - Tel. Thus the value a = 0 does not
mean that the specific heat remains finite at Te , it just means that it diverges
more wea y an any power 0 e . e v ue 0 e IS on y v 1 or
the Ising model on the square lattice, whereas the exponents are valid for
any two-dimensional system whose critical phase transition has the same
symmetries as the Ising model.
We have alread seen in the case of ercolation that a finite s stem allows

finite size scaling, which is also justified by renormalization theory, is valid


for the Ising ferromagnet as well. A finite system has no phase transition to

Let L be the length of the side of a square with N = L 2 spins. Asymp-


totically close to Te we have, analogous to (5.27):

By setting IT - TelLl/v = constant, one obtains


194 5. Monte Carlo Simulations

dimension 2, 3, or 4):
'Y 2 d-'Y/ v
vd+ a v d+ a v

Algorithm

and
(5.60)

L1E = H(S) - H(S') is easily calculated, for we have

(5.63)

The term hi is called the internal field of the spin Si. This finally enables us
to formulate the Metropolis algorithm:
5.5 The Ising Ferromagnet 195

,
models of statistical mechanics. We will also apply it to difficult optimization
problems in the next section. Because this method uses random numbers, it

,
at a constant energy (microcanonically) or use a trick to surmount high en-
ergy barriers. The Metropolis algorithm, on the other hand, is simple and

any arbitrary initial state, since the system always relaxes into thermal equi-
librium. At low temperatures, though, other initial states may have long

i = 1, ... , L.
196 5. Monte Carlo Simulations

void 8etT(double t)
{

- ,
bf[l]= exp(-4./temp)*RAND_MAI;
bf[2]= exp(-8./temp)*RAND_MAI;
}

With the Boltzmann weight factors bf [ ... ] thus defined, the innermost
loop becomes
for(x=l;x<L+l;x++) for y=l;y<L+l;y++
{
e=8 [x] [y] * (8 [x-l] [y] +8 [x+l] [y] +8 [x] [y-l] +8 [x] [y+l]) ;
if( e<O II rand()<bf[e/2] )
{

Ch=(8[X] [y]+1)*15;
poke(VSEG,v,OxfOOlch);
}

for(x=l;x<L+l;x++)
{
8 [0] [x] = 8 [L] [x] ;
8 [L+l] [x] = 8 [1] [x] ;

very fast; by comparison, putchO or a graphics command would slow down


5.5 The Ising Ferromagnet 197

The Monte Carlo simulation can be programmed with little effort. With
short programs and fast computers one obtains results easily. Analyzing the

task. Add to this that quite frequently hidden correlations in seemingly good
random number generators have led to systematic errors.

The PC program ISING simulates a 20 x 20 Ising ferromagnet on the square

,
size L, and for a r = ITi - Tjl L the correlations (SiSj) decay as a
power of r (a = lattice constant). At T = 0.8Tc , the system is magnetized,

Fig. 5.10.
ferromagnet in thermal
equilibrium at Tc
198 5. Monte Carlo Simulations

,
energy barrier of the order LlE = J L has to be scaled, since a wall between
positive and negative magnetization has to form, which moves through the

o ,
kBT = J, to ~ 10- s), therefore, we obtain T ~ 10 s, much longer than the
4 40

universe has existed. Consequently, we will not be able to observe a reversal

Fig. 5.11. Diffusing do-


. Igdl'ill fen'cmlagnet: ~lllli~N .. , .
main walls of the ferro-
tflmpmatum T"O.39T~ ... ma9n~ 111"10.041
5.5 The Ising Ferromagnet 199

At Te , the relaxation time r(T) diverges as


-z/v

merically, even for the two-dimensional model (z ~ 2.1). Near Te , the fluctu-
ations of the magnetization not only become larger, they also become slower.

Exercise

,
particles can only be at the lattice sites. This is described by the variable
ni which takes the value ni = 1 (0) if the lattice site i is occupied (vacant).
. . .

particles are to repel each other so strongly that no two neighboring sites can
be occupied at the same time.

corresponds to the magnetization in the Ising model. Only if the degree of


coverage falls below a certain level will the two sublattices be occupied with
200 5. Monte Carlo Simulations

1. Randomly select a lattice site.


2. If the lattice site is vacant, occupy it if this is permitted, Le., if all nearest
nei hbor sites are vacant if it is not ermitted acce t the old confi u-

3. If the selected site is occupied, draw a random number r E [0,1] and


compare it to z-l. If r is smaller, remove the particle; otherwise, accept

ceptibility, as a function of the fugacity z. Determine its critical value Zc and


the corresponding degree of coverage Pc of the lattice, where p is the ratio of

Literature

Honerkamp J. (1994) Stochastic Dynamical Systems: Concepts, Numerical


Methods, Data Analysis. VCH, Weinheim, New York

5.6 The Travelin Salesman Problem

A traveling salesman wants to visit a large number of cities in as short a time


as possible. So he plans an itinerary, Le., an order in which he wants to visit

approach the ground state has been termed simulated annealing.


5.6 The Traveling Salesman Problem 201

,
permutations of the N points. Since each route can be started at any of the N
points and traveled in either direction without changing its length, (N -1)!/2
. . . 155

v n mp r.
N! increases faster than e and very much faster than any power of N.
One can easily figure out a regular arrangement of cities for which the shortest
round trip can be specified, but mathematicians are almost certain that in
the worst case t ere is no orithm t at can calcu ate the shortest route
in a number of steps that increases as a polynomial in N. The factorial N!
increases as Nl/2 (N /e)N. Using the methods of computer science, one can,
however reduce the task of countin out the aths to N 2 2N com utation

Although the numerical solution of the problem appears almost hopeless,


computer science has developed methods with which, in one concrete case,

(5.66)

with the constraint


N
2: Xij = 2 for all i . (5.67)
=1

in Sect. 1.9. By adding more and more constraints one can eventually restrict
202 5. Monte Carlo Simulations

S = (XI2'
. . X13, X N -1 ,N) designates one of the (N - I)! /2 possible round
. . .
, ,
us how we should proceed: We have to heat up the system and then cool it
down very slowly. If the system is always in thermal equilibrium, then it has

is arge enou ow we can coo ow


thermal equilibrium all the time. Obviously P(S) will only be different from
zero at T = 0 if H(S) corresponds to the lowest energy (= the shortest route).

absolute minimum. On the other hand, the Monte Carlo method (at T > 0)
permits uphill steps as well, with a probability that depends on the difference

As in the previous section, this time can be estimated by using Arrhenius'


law. Let .dE > 0 be the difference in altitude to be scaled. Then a typical
5.6 The Traveling Salesman Problem 203

for the simulation - here, t is the actual processing time - should fulfill the
inequality

if possible. Therefore, as a function of time the temperature T may only

w v , r
optimization algorithms, which work with populations of paths.
Before we discuss the details of the algorithm, we want to estimate the

i=l

For N -+ 00, the right-hand side can be written as N(r), where (r) is the
average IS ance e ween nearest nelg ors. e now wan 0 ca cu a e r,
neglecting boundary effects; to this end we consider a sufficiently large section
of the plane, in which cities are distributed with a density p = N / L 2 Let
w(r)dr be the probability that the nearest neighbor has a distance between r
and r dr. In other w s r r i th fin i r
,
the circular ring with the area 27rrdr:
r

w r dr = 1- 27rrdr .
o
This integral equation for w(r) can immediately be transformed into a dif-
. r

resu ts III

If = -27rpr I with 1(0) = 1 . (5.74)


204 5. Monte Carlo Simulations

f (r) = e- 1rpr and w (r) = 21rpre- 1rpr (5.75)


The average distance between nearest neighbors can be calculated using w(r):
00

(r) = rw (r) dr = 21rp (5.76)


o

1
Eo>
-2
-LVii. (5.77)

can only be determined numerically; for example, Percus and Martin find
e= 0.7120 0.0002 in the limit N --t 00.
Algorithm

(5.79)

ways of turning a round trip S into a slightly changed path S'. For the sake
of simplicity, we will only present the following one: we randomly select a
. .

S' = (i 1 , ... , i p - 1, ip+l, ip+I- 1, ... ,ip, ip+I+ 1," ., iN) (5.80)

ber r E [0,1] is less than the Boltzmann factor exp [- (H(S') - H(S)) IT].
5.6 The Traveling Salesman Problem 205

2 2

6 6
4 4

randomly distributed in a square of size L. The array map of structures city


is used to store the coordinates (x, y) of each city:
t edef struct int x .
city map[MAXCITIES];

N is set to 100, but alternatively it can be passed as a parameter when calling

if(argc>l) N=atoi(argv[l]);

The order in which the cities are visited is stored in the array int path [N] .

llhile (! done)

anneal(path)i
if(count++ > DRAW)
{
206 5. Monte Carlo Simulations

The function event () examines the keyboard buffer. While the program

r uce e p eng
The function anneal (path) calculates the next. Monte Carlo step. The
position pos and length len which are needed in order to generate the new
, ,

if the difference de of the two path lengths obeys the condition


II

If this expression is true, Le., has the value 1, the move S --+ S' is accepted
and the standard function memcpy is used to copy the new path to the memory

{
double newlength,de,lscal;
int pos,len,newpath[MAXCITIES];

pos=randO*fl;
len=rand 0 *f2 ;
change(newpath,oldpath,pos,len);

ifann==l && (de < 0 I I frand() < exp(-de/temp) I I


(ann==O && de < temp
{

number generator which generates real numbers distributed uniformly in the


5.6 The Traveling Salesman Problem 207

l1n;f .1 Tf "",n ho ~1 .1". ~1 ",f fho 1.


. Af fho
-, fA1" .1
~ ~ r '0' A

V li:L

#define frandO (double)rand()/(RAND_MAX+1.)

Tne new patn IS generateo oy nrst copymg tne 010 patn toP) to tne new
one (np). Then the order of the cities between pos and pos+len is reversed.
The code for this is
....... .,; ...I - 'L
.....
( .,; _+
'
_ .... rl
r" J '
.,; _+ ......... rl
-r" J '
.,; _+
r ,
............ .,; _+ 1 .._'
-,
r
L

.LUI. .L'J.
.

memcpy(np,op,N*sizeof(int;
j=len;
for(i-O;i<=lenji++)
{
np[(pos+i) Yo N] = op[(pos+j) Yo N];
j--;
"\.
.
1.

.J

The algorithm for calculating the path length is obvious:


double length (int path[] )
t
l.nt l.,j;
double l=O.,dx,dy;

for(i=Q'i<N'i++)
.(
-i=(-i-&o1
J
"Iv.
dx=map[path[i]].x-map[path[j]].x;
dy=map[path[i]].y-map[path[j]].y;
,
1 += sqrt(dx*dx+dy*dy);
r
return U) j
}

Additional functions called drawDath and Drint draw the oath and write
fo.... + +". +1-. ..... .1. . .J , A 4-"+",... .,. ,,... +1-.",
...'"
v~ v

l:i:LH mse "He


V"

, .
VAA~.... .L

. 1#.1: CI. v t;; l. ljO


.. .L-

'~u~""
.. ~AJ'

ljIle
4 . . . . U~ . .

. on ljue
A.
~ U4"~

..
1"'A " b A ~".LA

ana
~

or decrease the temperature in the process.

Results

We have read the data from travel. dat into Mathematica and plotted them
there. Figure 5.13 shows the randomly generated initial state of about 100
ritipQ Thp. .H'7prt nath P from f.~7R) h~~ thp V~.111p P ,..." 4.R WI"
~4-
L:JUu..LU
4-
..- ~4- 1-
n .. u .... u. -
A

T
1

In D.
~
1

... 1-
...... .... 1 v .LJ v ......... au " ......'"
'. 1- ~'L . .1- .
v .......,J ...... 0 .... 'r , ..... ".........
system quickly relaxes to the value l ~ 2.2, with about 20% of the attempted
208 5. Monte Carlo Simulations

Fig. 5.13. Randomly generated ini-


tial state with a normalized ath
length l = 4.8

path. To answer this question we need the relatively involved methods of


computer science. But one can certainly recommend simulated annealing as a
5.6 The Traveling Salesman Problem 209

19.. e roun np or e same pro -


lem as in Fig. 5.14, but generated with the
threshold algorithm. The result is a slightly
shorter ath with l = 0.858
210 5. Monte Carlo Simulations

Here the reader is to try and solve the optimization problem from Sect. 1.3
with the methods of simulated annealing. A signal with a given power spec-
. . .

, ... , ,
voltage H(S) = maxr IUrl. In each Monte Carlo step the configuration of
phases is modified randomly, for example by varying one randomly selected

Literature
A. First Steps with Mathematica

.. I ,7 . 7 ..
.l::S ollaJ.lI\Ju W.lL.l.l

L.l.l~
7 . U.l.l
7 ..
iU.l ..
-
.
Un systems with a graphical user interface this is sometimes accomplished
by clicking on an icon. Mathematica comes up with the prompt In [1] := and
awaits an input which is terminated by RETURN. The notebook version of
Matnematzca IS Just Slightly ditterent m that commands are sent Indlvlduauy
or in groups with SHIFT-RETURN. Mathematica is an interpreter language
that processes input immediately and presents the result on the screen in the
form Out [0 0] = .... In doing this, all expressions which were defined earlier
in t.hp ~~.mp
. arp .1 int.o ., Onp pnr1~ ~. J I .. .LL .L.

. , -.. .... rnL , _. .


.L T. r

-
YV 1.111.1. ~.U

systems accomplishes the same thing.


L 0 o.J 0
... r'1.

T"\
.I.. J.J.\J
TT.
VI. ,-"VH.I. n.vl.I .I.J Viol. V 1.1.1......

The command math starts a Mathematica session.


In[. 0]:= Quit ends the session.

......
&
.1 ...
r:L.I.
..L 1 .
In [1] := 4 + 7
Out[1]= 11
InL2J:- 3 4.2 space = mUltzpll,catzon
Out [2]= 1206
In [3] := 2*3*4 * = multiplication too
Outf37= 24
in L4J : - :;& II Ii' I - al,Vl,sl,on
Out [4]= 3
Tn r.':;1 0 2"-:t "
.
-

DutL5J- 8
In [6] := (3+4) "2-2 (3+1)
-.. Ai
-n.. +- .f1:1-
In [7] := %/5 %= the most recent result disvlaued
212 A. First Steps with Mathematica
41
UutLIJ= -;-
OJ

In [8] : = N [%] N[x] = numerical value of x


Out [8]= 8.2
T'nral.-?? Alit::. n?':l 1n"'?':l\

Out [9]= 3.71908 10- 23


In [10] := 3 "'-2*36+' Order of precedence: power before

n, rof "'"1_ 0

The Most Important Functions

In[ll]:= Sqrt [16] Sqrt [x] = -IX


Out [11]= 4
P" II L:L
~J.l L .L.&.J - ...... L ~ ... , .. J ~ JVI". VJ/I

nut- f1?1 = 1 h70A


In [13] : =Sin [%] Sin [x] = sin x
Out [13]= 1. 1. = 1.0

All functions, procedures, constants, ...


available in Mathematica begin with a capital letter.
~ . . .. .
....
l'Unc-.;lOn argumen-.;s are always pmceu m square UraCKel.S L J
..

In [14] := Cos [Pi"] Cos [x] = cos X


nu t; r 141- 1 p.T.f1r.t 71f1I'IJ.p.
Sqrt L2J
In [15] : =Exp [0.5] Exp = exponential function
Out [15]= 1.64872 numerical value
In [16] := Log[%] LOJl: [x] = In x
.. ...
UU"'(; L.LOj- u. 0

In [17] := ?Log
Log[z] gives the natural Logarithm of z (logarithm to
base E). Log[b. z] gives the logarithm to base b.
In[17]:= Log[E, %15] %15 is the same as Out [15]. All In En]
and Out En] generated during a session
"n .... hD
- -"~ JIn
-- -- nnn .....
~

Out [17]= 0.5


A. First Steps with Mathematica 213

In [18] : = Sq:rt [-1]

1 represents the imaginary unit Sqrt[-l].


In [19] := Exp [I*N[pi/4]]

In [20] : = Re [%] +I*Im [%] Re [z] = real part of z


1m [z] = imaginary part of z
171

ArcCos ArcCot ArcCsc ArcSec ArcSech ArcSin ArcSinh


ArcTan ArcTanh ArcCosh ArcCoth ArcCsch
In 1 := ArcTan [1] ArcTan x = arctan x
Pi
Out [21]= -
4

In the following we will omit the input and output designators In [ .. ] and

ParametricPlot [{Cos [t], Sin[t]}, {t, 0, 2Pi}] Parametric


plot of a circle. An ellipse appears on the screen because the axis ratio is not

,
Show [ .. ] displays graphics objects with the selected options.
214 A. First Steps with Mathematica

A
ParametricPlot3D[{r Cos[t],r Sin[t],r 2},

ContourPlot[Exp[-(x-1)A 2 - y A2]+ Exp[_(x+1)A 2 _y A2],


{x,-3,3},{y,-3,3}, PlotPoints -> 60]

Options [Plot] A list of the options available with Plot [ .. ].

e most Important p 0 cornman s:


Plot[f, {x, xmin, xmax}]
Plot3D[f, {x, xmin, xmax}, {y, ymin, ymax}]

ParametricPlot3D[{fx,fy,fz}, {s,sl,s2}, {t,t1,t2}]


ContourPlot[f, {x, xmin, xmax}, {y, ymin, ymax}]

Symbols and Self-defined Functions

n =
N [n] ---t 2.4329 10 18 , the variable n has the value 20!
e-

N[a, 13] ---t 0.2968512129099, the number a to 13 digits. If not

C = (a+b) A3 ---t

3
A
f[x_]:= Exp[-0.2S x 2] Cos[4.S x] This is how functions are de-
fined. x_ zs a "place holder" with the name x. The underscore character in

f [1. 5] ---t 0.50882, value of f for x = 1.5.


A. First Steps with M athematica 215
r
'PII'I _ ... r I: r '1
--'''-J''
_ - - . - ..... ' l.. ' J .".'" J
'PlIO:
" . ... 0: 1 'I Dl . ~
... .",., v
..t ~J,. .t. ..1-: ~
4
..J
.
.c. ..J ,J.
~~~~~
T .1- ..J

OJ x one can use any omer variame name nere as weu. une oowins me same
result with the commandPlot[f[t] ,{t,-Pi,Pi}] .
fermi re_.b_l := l/CExnrbCe-lll +ll A function of two variahle.~.
Plot[{fermi[e,lO], fermi [e,Xnfinity]}, {e,O,1.7}] Plot of
two Fermi functions. Infinity = +00 .

.......
'TIL
~
n- 1.
ov'Vu 'V'V .- ..J
........u
- &
1 .1 L
UJ a..<" &
1
.
a = Random[]
The right side is evaluated and the resulting random number is assigned
+,." +l,." ..."' ...; '" 1-..1" _.
_ ...., 'V"J .. t'
+,." _ ..n;l1 ...;,,1..:1 +l,.;" ~ .........1-.."..
u'V U'V ~ u'V _ .,. J 'V..... uu

r:= Random[]
The right side is not evaluated at first, only after the variable r is
referred to again. The right side is reevaluated each time r is referred
to. Each time a new random number is oroduced.

Lists

numlist = {2,3,4} A list with three numbers. Lists are written in curly
braces {} .
- .. r_ _'1
-.
.: .... , --I. r ..
----.
,",,+
~~~
'1":'1
::J
..
., ",,'" "
'V~_ ~ J.
..J ....._ , .. '""+
_
,;",,,
v_
1';",1-
vv_
~

numlist"'2 ~ {4,9, 16}. Almost all functions are Listable.


Log [numlist] II N ~ List of the logarithms of the elements of
num.l1Sl;.
Table [2, {7}l ~ {2,2,2,2,2,2,2}. Table [ .. ] creates lists.
Table [i"'3, {i,S}] ~ {1, 8, 27, 64 , 125}
J.
.
J. J.
~
J. J.
.........' .... r1/.;
.. . 06.
.1.;
l06
":t
..J.
Dl., --I. J J.
l3 ' 4' 5' 6 ' 7 ' 8 J
1

Table [x, {x,O,2,O.2S}] ~ {O, 0.25, 0.5, ... , 2. }

Table [expr, { } ] generates lIsts. The braces, WIth the general


form {i, imin, imax, di}, are called 'iterator'. Abbreviations of
the general form are possible.

.. .
.&.;;1".-.- .. . .. .L\X,
,. .LXJ."I ' ,. -
\X,.,.,u.U;;JIJ, . - --".
216 A. First Steps with M athematica

A . , ( \ !:lftor !:In . ...... tho nov+ n,,+ . 1.


r
\. f .. Tn

spite of this the variables have the assigned values.

1I1S'C~J.O'CLJ.1S'CJ
-
L15'tl'".lo't L J ptOtS (UStS OJ) aaw.
letters = Table[FromCharacterCode[j], {j,122,97,-1}]
--+ {z,y,x,w, ... }
Sortlettersl --+ ~a.b.c.d.... 1. Sort r.. 1 sorts not onl'll letters
v ... .,
~ln~
J..n .I- .....vV' J.
v.

letters [ [3] ] --+ x, the third element of the list letters. Parts of
lists or of expressions are designated by double square brackets [[ .. ]] .
. . . . . . . "
lIeng'CDLJ.1S'CJ ----? 'U, we tengtn OJ we USt .l15't .
list [ [20] ] --+ {2.95, 1.91077}
J.1St [[::lO, J.)) --+ :l.~b

J.1St [[:lO,:l)) --+ 1. ~IUr(

abc = Reverse[letters] --+ {a,b,c,d, ... }


abc [ [-{ 2 , 41 , 6 }] ] --+ ib,d,f}
abc [[-1]] --+ z. A negative index corresponds to reverse numbering.
Pe~utations[{1,2,3l] --+ all permutations of {1 ,2, 3} .

Storing, Reading, and Fitting of Data

..... ._rn ..... _'-_ ..... n'


I. .I
fll~~_n ~11 n~l./ J . .J::.
""'."'.... , v ...... -.I -"
J
v .....
J. J ~~A L
.......... J
.Jo" ,n
.
[x_] = 1.0 x"41 - 2.0 x"2 + 0.5 A fourth-order polynomial.

? --+ the definition of f [x] .


.
III~
- .. ......
.. ___ LoL LA.I , .. r
1. A,
.. _
'~. ~, ~. ~ J.I
.. _'I ..

r:= Random[Real, {-0.1,0.1}] Random[] (without argument) re-


turns a real random number between 0 and 1. Random [Type, Range] is the
m.nrp
v
.1
. fnrm.

data =
Table[{x, [x]+r}, {x,-1.S,1.5,0.OS}] II Chop
Noisy data. Chop replaces real numbers which deviate from 0 by less than
10- 10 with O.
p:l = L1stPJ.ot[data)
Show[pl,p2] Show[. .] can combine graphics objects.
A. First Steps with Mathematica 217

dat.a list. .dat. Objects in Mathematica can be written to a file with


filename.
zng

!!list..dat.

zs comman
dat.a2 == dat.a ~ True. == is the logical equality operator.
OUt.put.Fo~ T measure at.
! !measured. dat measured. dat could be a data file that was generated
in an experiment.

model [x-l =a A
+ b x + c x 2 + d x 3 + e x 4
A A
We define a
model function whose arameters we want to fit.
Needs [Statist.ics'NonlinearFit' l zs comman
package NonlinearFit.m .

Simple Mathematica Programs


218 A. First Steps with Mathematica

(.* Th1S 1S the Iormat Ior comments 1n Mathemat1ca *J


Clear[" Global'*"] (* clears old definitions *)
f [x..] : = Tan [x/4] -1
... ..... r .....
r .LOl;; LI LXJ , t X, L. , &t JJ
,

r = FindRoot[f[x]==0,{x,3.1}] (* 3.1 = initial value *)


pi = x I. r

program.~.m ~ rwts r lXJ ana returns me vatue ~. 14_:>~, an


afmroximation of 1r. FindRoot r.. 1 finds numerical solutions of eauations.
N[pi-Pil ~ 8.88178 10- 16
The next nroQ:ram stored as Droll'ram2. m uses the M athematica function
n, __ r 1 ... ~..1
1~
...
.."
~ ~
........ '-&
,1
",f: .}.,. .... ro. T (~\ T .}.,. . . . .n. . . . . . "'. .
u .... ~ ......... u _ ~~ .. ~ ... ~ .. u .... ~
JO_
"n\~J' ~u

uses the fact that, for n > 0, the first zero of In(x) lies approximately at
n + 1.9n1 / 3 and that the following zeros are all separated by about 7r.

'L
! 1 '7.~rn n r lr 1 .=
Block[{f,start,rule,zero,list},
f [x..] = BesselJ[n,x];
start = Ifrn==O 2.5 n + 1. 9 n""(1/3)1'
"
oL .... ~'W ..
1:'': -,n
-
f.t: f '
"oL ...... ."
_.n
v, l( .... ' ..............11
J.",
zero = x I. rule; list = {zero};
While[Length[list] < k,
rr
---- ----LL ........ . -,
-.... , 0; .. + _1 1 1 ..L no;
..... r
rUl.e = r1naI\OOl;;LILXJ--V,tX,Sl;;arl;;JJ;
zero = x I. rule;
AppendTo[list,zero] ];
If[n> 0, PrependTo[list,O]];
Plot[f[x]J~x,O,list[[-l]]+l~];
list ]

-m
~~
- -
'L
" r":t 41 --4 PInt nf . T.' . thp ..fir.flt ..fn'll.r 7.prn.fI nf..
.T.,-,( , and a IiJlt nf
J3 (x) .

T ........ ,1 ,.~
'I;
-~.- -"
Do[Print[R Hello World Rl,{20}l ~ Writes Hello World to the
screen ~u umes.
A. First Steps with Mathematica 219

T.nnnQ
. -

Do [expr, {iterator}]
.
...... .. .L----'
For [start, test, 1ncr, body]
... 'L ..!I.
_.I
_.

Nest [2:, expr, nl


NestList[f, expr, n]
FixedPoint[f, expr]

... -
""'..
n .....
, ""'.. - . .. n
, ,4
...... .J ...0
...,.... ." ..., ... ~",
.1.
"'.Y~'

Do[Print[sl,FramCharacterCode[j],s2,j],{j,65,75}]
Writes the first 11 capital letters and their ASCII codes to the screen.
For [1=J., 1 < J.J., 1++, Pr1nt[1," II
,1 ;all ~ lienerates
the numbers from 1 to 10 and their squares.
... .= I . = - r 1 ~ n A.\
-- .
..
~ n".,
tAnll'; , .. r'"

tween 0 and 0.8.


-
. 'D ....;n.. r.11
-
&.

--- -J .(n'l,r .J 'L


hp-

Nest [Sin, t, 3] ~ Sin[Sin[Sin[t]]]


-
I' D'- LD;LU,
. - ---
~.~, ~UJ n.:;
..
, uu"
In",
1;"t:1(""t:Ur ,.)v UruUr
I
W1;",,,
,I ,I
,,"'t:
I

value 1.5.
NestList[Sin, 1.5, 30] NestList [ .. ] yields a list of all values cal-
thp thp .
I I .j"., n(
- .
f[x_]:= N[Cos[x],18] numerical value of cos x to 18 digits.
FixedPoint[f,1/10] 0.739085133215160642, the fixed point of
\.-U;:);L,
II
li.e;., ",.e;;L JUI
I' I' ,
\.-U;:);L
~
.
;L c,u
rr
~l.IIJJ
.
......... l.II, ...... y.

If [Random[] < 0.5, Print [Onumber < 0.5]]


beep: = Print [11\007 11 ] ; beepbeep:=(beep;Pause[l];beep)

~I:L.Ka LJ < .~, Deep, DeepDeepJ


theta[x_]:= If[x <= 0, 0, 1] Definition of the e function.
Plot[theta[x],{x,-2,2},AspectRatio -> Automatic]

Differentiation, Integration, Taylor Series

\,;~ear L _..,...a~ *.0 J


D[Exp[x"2], x] ~ the derivative of exp(x2 ) with respect to x.
220 A. First Steps with Mathematica

Simplify [D [%, x] ] ---+ the integrand of the above integral. The function
Simplify [ .. ] reduces fractions to their least common denominator and tries
to put the result into the simplest possible form.
---+ t e e nzte zntegra 0 e

integration with Nlntegrate [ .. ] .


A dou-
e imits

Head [series] ---+ SeriesData, a Mathematica object in its own right,


not a polynomial.

Timing[Series[Exp[Sin[x]], {x,O,80}];] ---+ {11.54 Second,


Null}

Vectors, Matrices, Eigenvalues

r = Table[x[i],{i,3}] ---+ {x [1], x [2], x [3]}

Matrixl'orm[b] ---+ the matrix b .

IdentityMatrix [3] ---+ the 3 x 3 unit matrix.


A. First Steps with M athematica 221
-..... __
,
-
'L

- r ..... '
L-" r ............
T. 1. 1.
... "oJ ., ".., ......
T.
..
r'L ,
LLlJ

yieLas me transpose OJ D

Det[b] --+ the determinant of b .


voor ---t me scaLar proauct OJ v ana r.
boov --+ the matrix b applied to the vector v .
bood --+ the matrix product b times d .
booJ:nverSe[b) --+ the un'tt matnx; Inverse LbJ Y'telas the 'tnverse of
the matrix b .
Eigenvalues [b) --+ the eigenvalues of the matrix b . They are the
"'t:' 'V~ VJ
L
....
il. ..1 ..1
"n", .... -v, u:-, I:
. J.
'07
' J
, .1. '.1. I I .il.
,-,un .J . J .i l
U/"",,,
J
bin;
r J.

l;araano formUla.
nb = N[b] --+ the numerical approximation of the matrix b . The exact
.J .1.
nrp ... . J
~ h'l' oJ
..1
J .1. 'I1l9.th nn
.,
nf 10- 16
"
'III';
.- r,.,'h 1 ~ [() A7f\11Fi.
- ., "Aa
- l
() 04()Q()4Q , () ()()I'\L!A,.,. ... ')l
~
n J,j "f

of the eigenvalues of the matrix nb .


u = Eigenvectors[nb] --+ a list of the eigenvectors of nb .
_. -\oLoo ..
-.- L -\oLJ--J
L "7
J
",n::. '. ""u", fJoAI,
I."""""
~J.
".",(..c; "16C;., '" uJ
,.

nb are orthonormal, except for numerical inaccuracies of the order 10- 16 .


Sort[Thread[Eigensystem[nb]]] --+ eigenvalues and associated
J ~ J.
tn thp ~~~ ,':-1- .J~ nf thp. .J. 'DC>
oJ oJ ., .,
"

Solving Equations

FindRoot[Cos[x]==x,{x,l}] --+ {x - > o. 739085}, the solution


of the equation cos x = x. The brackets {x, 1} mean: seek a solution with
respect to x and start the search at x= 1.
F1ndRoot [i Cos [a*x] ==x, -a*Sin [a*x] ==-1}, ix, 1}, i a, 1 t]
Systems of equations can also be solved with FindRoot [ .. ] .
Plot[Zeta[x]-2,{x,loo2,3}] --+ a smooth function which has a
~'- ~ '~
"'t:'1 v .", "16t:' , U",!/t:' ...."flU'''.
FindRoot[zeta[x]-2==O,{x,2}] --+ an error message because the
function cannot be differentiated symbolically.
F1ndRoot[Zeta[x]-2==O,ix,i1oo2,3}}]
r- .1A ~
Th.9.(l J
Tf nnp
"
- .. -"
n .(ltnrl . ~ _J
.J nf nn
"
'. J n

variant of the secant method is used.


222 A. First Steps with Mathematica

.....
60
...!!II- .&. 'I ...
L ...... g --
_...
......g ,
r.
1.-' _VfJ
.ft. 1 J:!.
u.uuo
..J. . .1 1
.
Solve [eqns, vars] tries to find exact solutions.
NSolve[eqns, vars] numerical solutions of algebraic equations.
'I' .I
. --- -..--, -.... ,..
- ,, ___ r_
'"'
1
...... '"
......,.. 'V... " ....'V "'J "''''V''''''''''''
,..~
.. -.......- ....
l..

DSolve[eqn, y[x], x] solves differential equations.


NDSolve [eqns, Y, {x, XIIl1D, xmax}] finds numerical solu- .
tions of differential equations.

Solve[a*x~2+b*x+c==0,x] ~ the 2 solutions of the quadratic equa-


tion.
Solve [ArcSiD[x] ==a,x] --* {{x -> Sin[a]}}
A A
Solve[x S-Sx 2+1 == 0, x] Too difficult.
NSolverx~S-Sx~2+1 -= O. xl ~ 5 numerical values for the zeros
~.t .f.J.':A
VJ ", ...... ""1
.~.
.
DSolve[y"[x]==y[x], y[x], xl ~ the general solution of this
differential equation.
~~

D::iOJ.veLY'LXj==\;OSLX*YLXjj, YLXj, Xj lV 0 success.


NDSolve[{Y'[xl==Cos[x*y[xll,y[Ol==O},y[xl,{x,-S,S}l ~

a Mathematica obiect called InteroolatinfzFunction .


f rX..l = vrxl /. % This is the format that is used to convert the ob-
ject InterpolatingFunction to a normal function which can be plotted with
Plot[f[x],{x,-5,5}]

Patterns, Ordering, Sorting

Remove L"GJ.ODaJ. * . j
~1St - t~, ;&, :l:la), golD), x D, :l:LDJ, :J.", 51nLPJ ;&}
PositioD[list, f [_] ] ~ {{3}, {6}}, a list of all positions with
fr . ,1 . "

~ ~

Cases [list, _~ 2] ~ {Sin[p]~} , all cases with the exponent 2.


Count [list, _~ -l ~ 2, the number of all cases with any exponent.
n.1 . . . .,.. r1.; ... rhll --+ .(1 ? f r~ 1 yn r.
~ 4 ~i n -n l:ll amdi.'lt
" .1.' r .... , . ,. . .~ J " J ~

oJ 616 LLI.J Ull <:.


A. First Steps with Mathematica 223

. .. ...... " _ __ ' l .... '-J' u",,, ""''''''v/,,,


.
.......... "'fL .J

yzetas ne vame True. 1 nere are more nan .:)U Juncnons OJ ne Jorm *l.I wztn
which one can pose questions.
? *0 ~ all these functions.

Select [list, NumberQ] ~ {1,2,3.4}. NumberQ[numberJ yields the


logical value True .
,... r .. . .L. . - r........ L:L.LL.'L

l'ne exclamatzon poznt l!) zs the togzcal negatzon. l'he constructf,on expr L# J &
turns expr into an operator, a so-called pure function. # is replaced by the
argument.
- - ..:I
' ......
r , . r.L r: ..L
..,."".

Factor [term] ~ the argument of the function Expand[] above. In


some ways, Factor is the counterpart of Expand.
FactorTerms (term] l'actors out numencal coeJ:/1czents.
Co~~ect (term, y] ::jorts accort1f,ng to powers oJ y.
Coefficient [term,x"2*y"2] ~ 2, the coefficient ofx 2 y 2.
Coeff1c1entL1st (term, xl ~ the hst oJ the coeJ:/1cf,ents oJ the powers
ofx.
Apart [ 1/ (x'" 4 -1) ] ~ the partial fraction decomposition of 1/ (x 4 - 1) .
-
N[Sort[{Sqrt[2],2,E,Pi,EulerGamma}]] ~
{2., 1.41421, 2.71828, 0.577216, 3.14159}. According to what criteria
is this sorted?
smaller:= (N[#l] < N[#2])& sorts according to the numerical value.
N[Sort[{Sqrt[2l,2,E,Pi,EulerGamma},smaller]] Nowitisco~
.,.D,.+
L

~'Gdby~
CN' ~
~
CP ;:,-
~

.)0~

L
B. First Steps with C

main y use or extensive numeric ca cu ations, a


pact, and function-oriented programming style and the use of machine-
oriented graphics interfaces. In addition, e (as does Pascal) has the advantage
t at t ere IS a convement enVIronment or program eve opment WIt a Ul t-
in graphics library for the PC.
e also has disadvantages, however: for one, it was not developed for sci-
entific calculations. Powers are calculated with a function, the mathematics

ondly, one often has to use memory addresses, and e does not control whether
indices accidentally exceed the previously defined range. Beginners in partic-

care;
float f, rational_number;
long long_i;
double Ion _f

ing int, char, and long are integers; those following float and double are
rational numbers. The different types correspond to different accuracies and

an ASCII character) is reserved for char, two bytes for int, and four bytes
for long.
226 B. First Steps with C
_ .... f t ( )

.
.r
int i;
fore i=4; i<16; i=i+l) printf(lIi=1.d \n",i);
~

~very commana nas to De termInatea Dy a semIcOlon.lne IteratIon lOOp tor


contains the following structure in parentheses: (initialization; termination
condition; increment or, more precisely, command to be executed after each
, ..,...
P~s). ~ne P
. are ~~ uy Lne LU ue execuLeU; sev-
.... .. . , . . .
eral such commands must be grouped by braces { ... } and there must be a
semicolon after every command.
This program is compiled with

"" 'v t"A ....... 1'.L ... u. ... "


and the command print writes the numbers on the screen. The print function
printf expects as its first argument a character string " ... II which contains
. . . .
tho tavt
-no.
, .
'
.. !llQ

'<J
uraH !llQ

1
tho ,.

uu Ult::: Ly pt::1::1 UI LUt::


,. . '<J

1
Lilt::
,. ..
fn.. tho

A~AA~" A A A O
. ,.
. 1.1 ..

.
tn ha

'<J
A

.
-l

are commonly used.

Format Variable type

%d int
%ld long
%c char
%f float (ftoatine:-noint renresentation)
II _
,..., -,=1_ ... + t. ~n 1
. .)
\' .& '.& 'J

%If double
%s string
rn.
~ lIt:: ~J AAA~~A
1 .
\11 11::1 a
. ,.
\,;Ua.1 avlJ'I:'~ LuaL
"

a
.. ,.
uut:: It::t::U. J.L \,;UI
Y.
.&

to the RETURN key.
, ,.
uy LUt::
.
A
,. . \, "J.
1 .
The formatting instructions above can also be used for reading, which is

. , "
wa.... .u. \ I
{ double i = 0.;
fore; i<100.;)
{ printf( "Please enter a number \n");
scanf{ "1.1f ll , I:i);
printf ( "You have entered 1.1f", i) ;
}
}

... .. .
ThiQ
.
.&'

1.1
~

1.
,-,au IJ'I:'
. .1,' -l
Q(lTllP
,1-
alJ IJII'I:'
.&

i:)all~'I:' IJIIII'I:'. M.
n
. 1 Tn t.hp t.vnp
T"'"
or 'J
. .. "
..
.&
-l

-l
auu
t.hp

instructions can be used in the for loop. 3. If one passes a variable, here i,
B. First Steps with C 227

vector.
main 0

str[99] the last character. str is the address of the vector (= the address
of the first element, or &str [O])j therefore it is sufficient to pass the name
. .
,
marked with the ASCII character \0 (= null). printf prints all characters
up to the character \0.

#include <math.h>
II

in the header files math.h, stdlib.h, graphics.h, time.h, etc. The line
#def ine N 1000 causes the symbol N to be replaced by the symbol 1000

sum = a+b;
a = b = alb * e;
mod = a 1. bi
228 B. First Steps with C

C contains abbreviations for some of the most common arithmetic operations:


the commands above replace the expressions sum = sum+a;, a = a+1;, and
b = b-1 r i I.
a>b; greater than
a>=b; greater than or equal to
-- ,.
a -- equa 0
a!=b not e ual to
a<=b; less than or equal to
a<b; less than

the value 1, otherwise it is assigne the va ue O. There is no speci data type


for logical expressions; C simply works with integers of type into

,
Logical operators combine logical values and produce 1 (true) or 0 (false).

if (b==O) printf ("Division is not defined");


else printf ("Result = Y.1f". a/b);
if (b>1.e-06)

The instruction if executes the following command only if the expression

,
have to be present, and multiple commands have to be grouped into a block
{ ... }, as shown in the second example.

case'e' : exit(O);
case'f' : scanf("y'lf".&:a); break;
case's' : scanf("y's".str); break;

instructions can be

,
variable ch, and then the case instruction that contains the corresponding
B. First Steps with C 229

This command causes the program to jump to the end of the switch block
{ ... }.
for (sum=O. i=O i<N i++) sum +=arra [i] for()

printf (liThe character 1.c vas entered \n",ch);


}

double v[6];
double u[5]={1.0, 1.5, 0., 6, -i.};

,
The indices run from 0 to (length-I) and are referred to with square brackets.
Thus v [5] has the value 1.5; v [6] is not defined. Vectors can be initialized

double mat [6] [5];


for(i=0;i<6;i++)
{

Matrices are declared and referenced with two indices. A separate square
bracket is necessar for each index. The first index indicates the row of the
matrix, the second indicates the column of the matrix. In the example above,
the vector v is the result of the multiplication of the matrix mat by the
vector u. The matrix has 6 rows i = 0 5 and 5 columns . = 0 ... 4. mat

.,
pass matrices or rows of matrices to functions.
230 B. First Steps with C

,
scanf ("%If", a);
value = *a;

, ,
at this location, and the value stored at a is assigned to value. The command
scanf("%lf" ,&:value) would have yielded the same result for value.

sin (x)

asin x
acos(x)
atan(x)

sinh(x)
cosh(x)
tanh (x)

log10(x) Logarithm to the base of 10, IOglO(X), x >0


pow(x,y) xy

fmod(x,y) Remainder of x / y
These mathematical functions return a value of type double. They have to
be declared beforehand with #include <math.h>. If the ar ment is not of

double r;
r = rand() / (RAND_MAX +1.);

between 0 and RAND_MAX. If one needs real-valued random numbers in the


interval [0,1], then one can divide rand 0 by RAND_MAX. To do this, however,
B. First Steps with C 231

DAlTn MAY ..... 0


"

#include <math.h>
main()

double f(double),x;
for(x=O.;x<10.;x+=.5)
printf("\n f(1.3.1lf) = 1.4.2e II ,x,f(x;

--{ ---- - ---,


double x2;
x2=xxx*xxx;
return (x2*exp(-x2/2));
}

One can define one's own functions, here f(x) = x 2 e- z2


/2. To do so, the func-
+;~_ l.~n +~ l.~" , ;_ +l.~ .11' 1:.. (l.~_.n __ ,:_1\ \ ~..,.~ +l.~_ ' ro -,

wnn tne type aeCIaratlOns lOr tne IUnCtlOn as weu as lOr tne arguments. .1 ne
commands of the function f (x) are enclosed in braces { ... }, and the value
of the argument of the return statement is returned when execution of the
function completes. If no value is returned or no argument is passed, then the
type void is used. Only the value of the arJ?:ument x is passed, so f cannot
change the value of the variable x here. If, on the other hand, ix, the address
of x, is passed, then f can also change the value of x:
-
it,
. .. . ..11'

main\J
1.
double f(double *),x=O.;
while (x<100.) printf (II \n f (l.lf)=l.lf" ,x,f (&x ;
}

double f(double *address)


{
double x2;
,.., .. ", .. "
-.0,

In this case. double* indicates a pointer to a variable of type double. The


'J "

or even other functions are to be passed to a function.


main 0
1.
double u llOOJ , v llOOJ ;
double ScalarProduct(double *, double *, int);
int n=20,i;
232 B. First Steps with C

, . .
printf(" \n 1.1f \n",Sca1arProduct(u,v,n;
}

double Sca1arProduct(doub1e u[], double v[], int n)


{
int i;
double sum;
..

memory location for a vector is reserved in the function; the processing is


done with just the address of the first location. u [3] counts three positions

n.
double MatrixFunction(doub1e mat[][10],int rows,
int columns)

With matrices, too, only the address of the first element &mat [0] [0] is
passed, but the program also needs to know the length of the rows (here
10 in order to address eac e ement. us tee ement mat i . IS at t e

rows allocated does not have to be known.

Variables can only be used within the function in which they are defined.
If they are to be valid in more than one function, then they have to be
declared before those functions outside of an curl braces. u v n i and
ScalarProduct can thus be used in all functions (and will have the same val-
ues everywhere); sum, on the other hand, can only be used in ScalarProduct.
void si nifies that no variables are assed. Of course now the function can-
B. First Steps with C 233

.A . . rJ1-~~~'
...........t'''''

We want to list some common errors which unfortunately do not produce


error messages In many cases.
b = mat ri il
-
Matrix elements have to be referred to by two indices, each in square brackets,
for example mat [i] [j] . The command above calls i, then j, and assigns the
element mat [i] to the variable b. mat [i] . however. is the address of the ith
rmn (,...
\
Irm... + r; 1 rnl)'
~J~ ~ '~/'

if (a=b) dosomething 0 ;
'T'l...~
.a. ........ r .......... 1
'-'
.4- 4-
uv uJ P"" u.
.1. 'T'1
- u. .a. ........
v
,.1
~~~.~
.1-
'-'

o to tne vanaDle a ana tnen tests wnetner tne valUe OI a IS equal to zero. 11
not, the function dosomething () is called.
integer = 3 * rand () / RAND MAX'
All ..........;<:\hlt:>'1 ~nr1 ~rt:> to. ht:> o.f t.unt:> ; .........._ C'
-" . -
1 I'ATYl_
-<;J

pilers evaluate this expression from right to left. In this case, the quotient
and with it the entire expression receives the value zero, since the remainder
i~ lo~t. in t.h p of t.wo Tl
1"
,. onp
" " tht:> _1 _1...] a1 _1
v &
1-
.. _1
..J 1 '-' L 1 11
L1 1"\ 1 ...] ()
I- J..l.l & "V ".... ~ v, .... , u..... u ~ .. -0

of the specific compiler version.


int vector[10],i;
for U=l; i<=10; i++) vector[i]=i*i;

Vectors of length N have indices between i=O and i=N-1; thus the last com-
mand of the for loop, vector [10] =100; ,assigns the value 100 to the mem-
ory location after the vector without any warning, and the programmer does
not know what is being overwritten!
main 0
{
,.h~,.. *n~m ...
~_":_+4' (IIt.n.~+ . : _ ......__ ~ __
r
................~..
\
,
II"/ II -
,... , "'QUi'"
J
.'\
I
--
?
- - - "
11\.
, ,
}

name is declared as an address of (= pointer to) a character variable, but the


oointer is not initialized anvwhere. This means that an unknown number is
stored in the variable name which is interpreted as an address; your input is
written to this address and destroys other data in the process. The compiler
issues a warning about this error. but it does execute it.
char msg[10] ;
msg =IIHello ll ;
234 B. First Steps with C
1\.T
l.'QU..U::;., VI.
.E
QI.'l;::;~
. ,I..lVlI
,_ 1
. lin." II .1 .1-
lIl..l'l;::;
11 J:
VI.

the character strIng, out the aaaress 01 the vector msg may not oe changea.
The following program eliminates both of the above errors
maine)
.(

char name[20],*msg;
printf(" \n What is your name? II);
scanf ("1.s" ,name) ;
1Il~6-
... ~ ~ .. t

pr1nl;:I \. \n I.S I.S \n , msg,nameJ;


l'

The difference between II x II and 'x' :


'T'h~ I"
. lQ ~ _1. ..... . It. lQ ..J nf t.h~ t.wn rh~r_
. . .A.
-~

_1
G.l1U
\,..
\V.
IT'l_
~L.n:::;
l
-A-
. .L., ~

Q
.
~

_1- A-
LLLQI. QL 1I't:'1.

int a=100;
scanf("1.d",a);

scanf mterprets a as the memory address numOer IUU and overWrItes What-
ever was there. The correct read command is scanf ("y'd II ,&a) ; .

T ..L

Kernighan B.W., Ritchie D.M. (1988) The C Programming Language. Pren-


tice Hall, Englewood Cliffs, NJ
c. First Steps with Unix

This appendix is intended to provide the beginner with a short survey on the
most important Unix commands. In addition, we will explain how to access
x r r
edit and compile these programs.
Nowadays there are many public domain programs for Unix, i.e., programs
which may be copied free of charge for noncommercial use. Several of these
ave ecome stan ar ro rams. orne wi e escri e ere or exam e

ask your system manager to install them. These programs are marked by the
symbol (*).

run "simultaneously in the background." "Simultaneous" means that these


processes share the computing time.

passwor, . ese are 0 alne rom e sys em manager. or every user ere
is a separate home directory on the hard disk, on which one's own programs
can be stored.
After entering the user name and password, you will find yourself either in
a shell- i.e. the com uter waits for commands - or a ra hical user interface
(usually XII) is started. In the latter case, if a window is not automatically
opened, one has to generate a window using the mouse. Then Unix commands
can be entered in the window and terminated with RETURN. Windows can

The following groups of commands will be described in this appendix:

C Compiler
We will not describe the following groups of commands:
236 C. First Steps with Unix

Let us point out here that graphical interfaces come with many auxiliary
programs (so-called file managers) which facilitate file management.

Files

u w y e,
and a number needs two to four bytes.
Every file has a name. This name can have more than eight letters on

compared to drawers. The root of this directory tree is indicated by the symbol
I. Subdirectories are separated by I
r I

users

Here, it is not apparent to the user if the directories are on a local disk or on
disks on other computers. The shell remembers a current directory. At the
,

it.

eters. Options are designated by the character - preceding them. If several


c. First Steps with Unix 237

.c.

c C source code

p Pascal source code (sometimes .pas is used instead)


o Object file (compiled program code, not yet executable)

tar A program archive produced with tar


gz A file compressed with gZip(*)

Help

y usm t e cornman man, one can IS ay t e escnptlOn 0 a cornman


on the screen page by page. Syntax, options, and parameters are explained.
For example, with the command man man one obtains the description of the
command man itself.

man -k keyword to obtain a list of the commands which contain the word
keyword in their one-line description.

FIle Mani ulation

A file can easily be created or modified with a so-called editor. This will be
described later. Text files can be displayed with cat, more, or less(*). more
dis la s the file a e b a e b usin less one can move around in the
text at will by pressing a key.
Copying a file can be done with the Unix command cp (copy). The syntax
is c in ut out ut. The file in ut is co ied to the file out ut. In order to
238 C. First Steps with Unix

renames the file old to new. This can also be done with directories.
A file can be deleted with the command rm (remove). rm file deletes the

The name of the current directory can be shown with pwd (present working
directory). All file names which do not begin with / are interpreted relative
to this current directory, as mentioned above. The command cd dir sets the
current director to dir. H the arameter is omitted then the user's home

Directories can be created with mkdir (make directory) and deleted with
the command rmdir (remove directory); the command mkdir temp creates
!

The command Is (list) is used to display the contents of a directory. With


Is dir the contents of the directory dir are displayed. The option -a causes

NIS (Network Information Service) - previously Yellow Pages - is often


used if one works on several computers networked together. Then there is

password is yppasswd.

outputs by inserting the characters < and > respectively. The output of a
C. First Steps with Unix 239

The Standard Editor vi

consortium, is used frequently as well. Here we just want to discuss vi, since
it comes as part of every Unix system.

At startup, the editor is in command mode. This means that the keyboard
in uts are inter reted as commands. 1m ortant vi commands in this mode

A Jumps to the end of the line and switches to insert mode (Append)

i Switches to insert mode (Insert)


Esc Switches back from insert mode to command mode

x Deletes the character at the cursor position

dw Deletes one word

G Jumps to the last line


/ pattern Searches for pattern
240 C. First Steps with Unix

:x Saves the document and leaves the editor (Exit)


:q
:q ! Leaves the editor, discarding changes (Quit)
:w Saves the document (Write)

Reads the file called file (Read)


: set nu Switches on line numbering (Set Numbers)
,
of text and copy them, or indent entire blocks.

The C Com Her

The translation of a C program into executable code is done in two steps. In


the first step the program is translated (or compiled) into an object file. The
h m i r

executable program.
The C compiler which comes with a Unix system is called cc. With the

-0 Optimizes the code

path
-Ix The linker links the library Iibx to the program

is
c. First Steps with Unix 241

In order to compile larger program packages, the auxiliary program make is


often used. It reads a file called Makef ile and processes the instructions given
there. wi .

Networks

IS sec IOn we WI
network.
Every computer connected to the Internet has an address. This address
consists of four numbers, each of which can vary between 0 and 255. Every ad-
dress has a name associated with it. ft . h sik. uni-wuerzbur . de for ex-
ample, currently has the address 132.187.40.15. The individual groups of num-
bers cannot be mapped to the components of the name in a unique way. For
exam Ie an address at the Universit of Wiirzbur . uni-wuerzbur . de

one should use the names whenever possible.

onnectIons to

The command telnet computer can be used to establish a connection to an-


other computer on the Internet. Here computer can be either the computer's
name or 1 s n erne a ress.

output if there is a physical connection and our computer is running:


Trying ...

(some machine-specific informations)

10 in:

At this point, the user has to enter his or her username and password.
One should always close telnet sessions correctly, i.e., leave the computer
via logout. If nothing else works, one can get to a telnet menu by using the
esca e character that is s ecified. The s mbol ...] used here means that the
CONTROL key and] have to be pressed simultaneously. Once in the telnet
menu, one can get short instructions via the command ? The connection can
be terminated with the command close.

changed explicitly by the option -1.


242 C. First Steps with Unix
r"' .
&&&6
'W'
& co
I"
&&v&&&
r't..L1. r"'
-r
&- . , .&.
""

In order to exchange files between computers there is FTP, a file transfer


protocol. A connection is established via ftp computer. Again, computer can
1.. . 1.. T , , TT , . , to
U1V GU. V.l a. .I..I.C.lC, IIVU, a. Ul)Cl lldl) IIU .y 111.11.1-

or hersell; the computer asks tor username and password. Alter a successful
login the following commands can be used, among others:
sP.ts thp. to to Lp.. t.hp n~.t.~. ~.rp to ,
hi .:I 1..
~

_.:~"I.. ~ 4-
.' '
~

as sets the transfer mode to ASCII (text mode). In this mode,


control characters may be suppressed. There may also be a
svstem-denendent conversion of the characters
Is lists the files in the remote directory (list)
cd dir changes the remote directory to dir
tzet file copies the file file from the remote computer to the local one
put file copIes the file file from the local computer to the remote one
mget files similar to get, but this command accepts wildcard characters
in t.hp filp ~mr1 to
, . filpQ
&

mput files similar to put, but this command accepts wildcard characters
in the file name and transfers multiple files

.. -.LranSler
.lnt;ernet; -~ ue
~
-
Many institutions offer programs which anyone may copy freely. These can be
obtained through the Internet, using FTP. To this end, special FTP servers
~ . A

olIer tne option or logging in unaer tne username I'&P or anonymous. ~ ne


password required is one's own e-mail address. For example, the programs
described in this book are available from the FTP server
z. . .,. .:-
-vrr&&J---~-
. .g._- ..:II .

,
\ l;Ullt:l.lL .I.e
TT'1o ,,

.. nn .. n ... ~n ..... ,
.I."~ .I.0'

.<j;V .I.tJj 11.1 Ll.lt:
"
,.
.y /
I I .
PUU/ ~t'~.1~.

Data Compression

In order to archive data it is useful to store several programs together under


one name. This is frequently done with the program tar (tape archiver). The
command tar cf file. tar dir is used to archive the directory dir with
all its files and subdirectories in the sini!:le file file. tar. With the command
. "" ,. . " f +'ha ' .
+...... + 4= 4= .; ,..... +...... Ana
,- ---_.
'
-- ~&&~
" f +'ha "",..;1 '-' ~_ V&&~ ~_ V&&~ ~ ~&& ~, ~&&~

with the command tar xf file. tar the directory is restored.


C. First Steps with Unix 243

'T'l...~~
.&. ,u",&&,
~~
&&& ~.&
,
.... "'.&
4-~
U~
~~
UU/
,~ -1:~1
'" ....&U&'- & , . ~-~
U/& ' "
,~ ..] A.
uu"'..... '-' &&'"
'*\ '.I.'
yA 'U'

rrequently usea program is callea gZ1p' '.lne commana gZ1p I11e com-
presses the file file. The output file has the name file. gz. To decompress,
one can use either the command gzip -d file. gz or gunzip file. gz.

XII across a Network

It is no problem to run XII applications across a network. i.e. to do the


, , . nn nno ~nr1 ,. , tho nn ~nnt 'hoY' T .ot 11Cl
-r
,, 'U'
.I.' ",
.I.'

W~ WaUL LU ;jLtLlL aU A r 'U'


UU Lll~ &
~ allU llav~ lL

display its windows on the XII-capable monitor of our local computer local.
First of all, we have to tell our computer to accept displays from the other
VUC.
rn1. . .1
.L 1.11., I., UVUC v 10,
.'L
A..LLViCI" ~
A, ,1..
ogWV "og. '-'II "IIC ~ ogWV "og
1..
W'V Ilo,V'V "V
-r
set the enVIronment vanable DISPLAY. tloth In csh and m tcSh thIS IS done
via setenv DISPLAY local: o. The symbol: 0 represents the first X session.
All X programs called from now on will send their graphics output to the
monitor ot local.

Literature
"'1', . .
. a..,
T.l" T'lo' -, C (1(\(\A\ Tl..n TT... :.r r\ C'l TTT'
l\T.nn.
~

_.IorK .& '-'. \,&,"''''.&1 ....u ' V " ' & & &. . .
..- ~ '-'J ~U'VA& &&'VJ' 'V
L

~'Gdby~
CN' ~
~
CP ;:,-
~

.)0~

L
D. First Steps with Xgraphics

,
library of the X-Windows system, and provides simple commands for man-
aging windows and drawing in them. The many parameters which have to be

adapted to the problem to be programmed rather than having to adjust


to the present size of the current window. The most important commands of
246 D. First Steps with Xgraphics

The program package, including the documentation, some demonstration


programs, and the X-Windows versions of the sample programs from this

The archives are unpacked with the command


tar xf <file>.tar

done as follows:
ftp ftp.physik.uni-vuerzburg.de

e username:
ftp

The computer asks for a password:


readerGyourhost.yourdomain

The correct directory has to be selected:

Now all files are copied:


mget *

y or n). Finally, the connection is closed:


bye

We want to use a simple example to demonstrate that just a few commands


are sufficient to display a physics problem on the screen. The example is
the random motion of a article random walk for which there is a well-

This is done in the following C program:


D. First Steps with Xgraphics 247

#include "Igraphics.h"

#defineMAII 640

main 0

InitIO;
mywindow=CreateWindow(MAII.MAIY."random walk");
ShowWindow(mywindow);

case 2: y++;break;
case 3: y--;break; }
}

Thus five graphics commands are enough to generate interesting movements


on the screen. The program, called walk. c, is compiled via compile walk

per e w m v
and the file has to be made executable via chmod u+x compile. The result
should be the picture shown in Fig. D.1. Then if one enters any character in

Isa ears.
Additional demonstration programs, which also show the other capabili-
ties of Xgraphics, can be found on the enclosed CD-ROM.

Liiders M. (1997) Introduction to Xgraphics. Postscript file on the enclosed


CD-ROM; also available via FTP from ft . h sik. uni-wuerzbur .de,

glewood Cliffs, NJ
248 D. First Steps with Xgraphics

Fig. D.1. Random walk consisting


of 250 000 steps on a square lattice
E. Program Listings

a most at ematiea programs an a ew 0 t e programs or t e


Unfortunately we cannot print all source codes, owing to limitations of space,
but all programs are available on the enclosed CD-ROM and can be printed.
e names 0 t e a ema 'tea programs ave t e orm name. m t roug ou .
The PC versions of the C programs, name. c, have been compiled with Turbo
C by Borland; the resulting executable files, name. exe, are available on the
enclosed CD-ROM.

first letter of each keyword listed is the key that controls the algorithm; for
example, exit means that the key e terminates the program.

/pub/cphys/mathematica/
/pub/cphys/unix/
/pub/Igraphics/

Additional information about the programs can be found on the World


Wide Web under the address

1.1 Function versus Procedure: sum.m and sum.c


Print[lI\n Function versus Procedure \n"]

sum=O. ;
Do[sum=sum+data[[i]].{i.length}];
average=sum/length
]
avera e [data ] : =A I [Plus data] /Len th [data]
250 E. Program Listings

"'.... orn ~

#include <stdlib.h>
#include <time.h>

ma1.nu
'l
float average(float *,int)j
int i;
clock t start.end:
ofl n::.'t: ...1_ ... ___ .... r1 nnnn, .
,.1 ') .
for (i=O;i<10000ji++) dataset[i]=random(1000)/1000.j

pr1.nl;J:\ \n 1 en l;nousanU ranuom numDers are auueu j \n


tn1.s 1.S repea'tea a nunarea t1.mes, W1.tn tne reSU.lt:\n')j

start=clock 0 j
for(i=O:i<100:i++) avera~e(dataset.10000):
nrintf( II average = Y.f\n" average (dataset 10000)) .
- -
end=clock 0 j
printf( II time= Y.f sec 1I,(end-start)/CLK_TCK);
,
getchO j
J

float average( float* data,int n )


{
float sum=O. :
int i'
ofn'Y'(i =n i <n' i ++) R11m:-
. ri 1
return sum/nj
}

.......... .. . .. ..
..........
... ~ ....T l'
. ...- ..........

Print ['I\n Nonlinear Pendulum \n ll ]


T[phiO_]=4 EllipticK[Sin[phiO/2]-2]
plot1:=Plot[T[phiOl,{phiO,O,3.14},PlotRange->{O,30},
Frame -> True, FrameLabel->{lI p hiO Il , "Til}]

sinuspsi[t_,phiO_]=JacobiSN[t,Sin[phiO/2]-2]
phinorm[x_,phiO_]=2 ArcSin[Sin[phiO/2]*
C!;
.. . rv Tr,., ;nl ....h;nll/....h;n
~- ~c .~ c
'C .~~

r--- . -.. ..... - .-..


_ .... ..:nr11 .rr 1 n..:1

phiO [2] =N [ . 8 Pi]


phiO [3] =N [ . 95 Pi]
phiO [4] =N[. 99 Pi]
pn1.u L:)J =1'lI L ~~~ 1"'1.J
flist=TableLphinormLx,phiOL1.JJ,'l1.,5.J-J
plot2:=Plot[Evaluate[flist],{x,O.,1.},
Frame -> True,
E. Program Listings 251

1.3 Fourier Transformations: fourier.m

"
f[t_]=(Sign[1-t]+Sign[1+t])/2
fs[w_] = Integrate[Exp[I*w*t], it, -1, 1}]/T II ComplexExpand
T=10

p2list:= p2list = Table[ Abs[ fs[ k*2 Pi/T] ],{k,64}]


->

PlotLabel->"Discrete Fourier transformation",


PlotStyle -> Thickness[O.O],
DisplayFunction -> Identity];

Show[gl,g2, )
252 E. Program Listings

{s,64}]//N
plot4:=Plot[{Re[fapp1[t]],f[t]},{t,-5,5}]
fapp2[t_]=Sum[N[fslist[[s]]*
+
onJugate
Exp[-2 Pi

lot5:=Plot[{Re[fa 2 t

1.4 Smoothing of Data: smooth.m


Print[ll\n Smoothing Data by a Convolution \n"]

, ,
SetOptions[ListPlot,Frame->True]
SetOptions[Plot,Frame->True,RotateLabel->True]
plot1 := p1 = ListPlot[Thread[Join[{xdata},{data}]],
PlotSt le->PointSize[.01]]

sigma= 0.4
kernel = Table[ N[ Exp[-x-2/(2*sigma-2)]],{x,-5,5,10./255} ]
kernel = RotateLeft[kernel,127]

smooth=Sqrt[256] InverseFourier[Fourier[data] Fourier[kernel]]


smooth=smooth//Chop
lot3:= 3=ListPlot[Thread[Join[{xdata},{smooth}]]]

plot4:=p4=Plot[BesseIJ[1,x],{x,0,10},PlotStyle ->Thickness[0.001]]

plot5:= (If[Head[p1]==Symbol,plot1];If[Head[p3]==Symbol,plot3];

1.5 Nonlinear Fit: chi2.m

plot1:= (gr1 = ListPlot[data,PlotStyle -> PointSize[0.02],


DisplayFunction -> Identity];
gr2 = Plot[Sin[t] Exp[-t/10.],{t,0,3Pi},
. . .

f[t_]=a Sin[om t + phi] Exp[-t b]


E. Program Listings 253

- ."_-.TT.

~ ':. _ _..
r. -" r.
L.... &. t ...... t " t . " , \oJ,
&. &.~ I
I A
."

_ - ~'i.l."

square[{t_ty_}]=(y-f[t])-2/sigma2
chi2=Apply[Plus t Map[square t data]]
find:=FindMinimum[chi2t{atO.9}t{omt1.1}t{phitO.1}t{bt.2}]
fit:=If[$VersionNumber>=3. t
BestFitParameters I. NonlinearRegress[datatf[t]ttt
{{a t 1.1}t{om t 1.1}t{phi t .1}t{b t .2}}t
ShowProgress->True]t
N"... 1 . ... i ... rit ....... .,r... 1 ...
II_ 1 11. I __ 1 ;1. .f_l.": ,,1.1.
t,";..- t . 11. t .fl..
:''L.. -t:. .. , t'
-~t t ... -t -.: -~ -~ .~ ~

- _ ... - '0' ' ........... oJoJ

pvalue[x_]=1.-CDF[ChiSquareDistribution[7]t x]
interval={Quantile[ChiSquareDistribution[7]t. 05]t
Quantile[ChiSquareDistribution[7]t.95]}
limlx_J=QuantilelChiSquareDistributionl4Jt xJ
plot2:=Plot[PDF[ChiSquareDistribution[7] tX] t{x t Ot 20}]

rule = If[$VersionNumber>=3. t
... ..... - I I _ 1
I
11. I __
N"... 1
1 11.
ft

I_l.':
rit ....... ., r... 1 ...
11. - Il.. ':'1.~' -
.
-.T ...
~r .. '
t"'L"oJt"t
~ ......
....- t - .
t ..--t -. t "r- t . t ..- t .. .. t
..... r .... ~
-~ -~ -~ ~ ~

{{a t 1.1}t{om t 1.1}t{phi t .1}t{b t .2}}]]


aO=a/.rule; bO=b/.rule; omO=om/.rule; phiO=phi/.rule;
chi2min = chi2/.rule
plot3:=ContourPlotlchi2/.{phi->phiO t om->omO}t
{a t .4 t l.3}t{b t -.04 t .2}t
ContourShading->False t
Contours->{chi2min+lim[.683]tchi2min+lim[.9]}t
P1n...Pn; ...... <:-~J;.n ~ ...hA1 -~~" .. " "h"'\.1

., _n, _v_r ..... " I ...y,u...


....._,u ................ I .. 1. ~ ' . ' n
r-- -'
A _'"
'y,u"'-t'" ............"l- t ~

{om t .90 t 1.05}t{b t O.O t .15}t


ContourShading->False t
Contours->{chi2min+lim[.683]tchi2min+lim[.9]}t
PlotPoints->50tFrameLabel->t"om"t"b"~J

g[t_]= f[t]/.rule I
step:=(data2=N[Table[{ttg[t] + .4 Random[]-.2}t
~1: n ~P; ~ p;lll
T-f: _.
r~"
- =~ .
-
____ A
~.
__ ________

-
I
_.
r..I
t-4=r..,

.. -.. t .. t
1.1 __ ''':
" ~."

{{ataO}t{omtomO}t{phitphiO}t{btbO}}]t
NonlinearFit[data2 t f[t]ttt
{{ataO}t{omtomO}t{phitphiO}t{btbO}}]] )
tab:= tab = Tab.leLtch12tatbtOmtph1J"!.stepttlUUJ"J
abtab := MaplTakel#t{2 t 3}J"ttab]
plot5:= ListPlot[abtab t PlotRange->{{.4 t l.2}t{-O.045 t .2}}t
AspectRatio -> 1 t Frame -> True t
FrameLabel ->{"a" "b"l Axes -> None
AlA _> Pn;"''''~;''ArO
~
Pl 01511
"
254 E. Program Listings
.. D
..... v
'1\ Jr. . . .
...
.. ..,
-.:-
. .. .. .- ...
.1 _
..........

Print[lI\n Multipoles for a Static Potential \n II]


SeedRandom[1234S67S9]
rpoint:={2Random[]-1.2Random[]-1.0}
Do[r[i]=rpoint.{i.10}]
p1=Graphics[Table[Line[{Drop[r[i].-1]-{0.OS.0}.
Drop[r[i].-l]+{O.OS.O}}].{i.S}]]
p2=Graphics[Table[Line[{Drop[r[i].-1]+{0.0.OS}.
n....nnr.... r;1 -ll-rn n nR~~1 r; c;~11
"'--
1"'"
' ..: __ r...
-~
_~,_rT.; __ rIn...._:r....
.. r';.L1:1 _11_fn
L ..... ' ' ....... .... no n"\. ....
-~~....

'r"-
r. r.
.~

..,
L ... - ....J
. J'
....
.~

r,..
'J

Aft A''''
.J-.-~v.vu.v.T.T.J .1. ....

r .... , ..
V.T.J ..
p4=Graphics[{Thickness[0.001].
Table[Circle[Drop[r[i]. -1]. 0.1]. {i .10}]}]
SetOptions[ListPlot.Frame->True]
SetOptions[Plot.Frame->True.RotateLabel->True]
plot1:=Show[p1. p2. p3. p4. Frame ->True.
AspectRatio -> Automatic.
PlotRange -> {{-2. 2}. {-2. 2}}.
_'L .... 1 _,- Illy"-II .. II "\.1 9
oJ ~
J~

.. r
U.l.D"L.I.-_.D_"I-~''''
.. - r, ., ,
0 ' . , ... O'.J."
pot[rh_]:=Sum[ l/dist[rh.r[i]]-l/dist[rh.r[i+S]] .{i.S}]
plot2:=Plot3D[pot[{X.Y.0}] .{x.-2.2}.{y.-2.2},
AxesLabel->{l x l,l y ","Phi"},
PlotRange -> {-S,S}.
PlotPoints->40]

plot3:=ContourPlot [pot [{x,y,O}] .{x,-2,2},{y,-2,2},


n1_+n.. . .; ... +C!_~4n
,.. _.
... ~_ ..: ....'CO_1 __ , Ay__ T _~_, _ .... IlIyll
~ ,
II II"\.
J J
1
",

quadrupole[r_]:=Table[3 r[[k]] r[[l]] - If[k==l,r.r,O],


{k,3},{1,3}]
qsum=Sum[quadrupole[r[i]]-quadrupole[r[i+S]],{i,S}]
magnitude[r_]=Sqrtlr.rJ
dipole=Sum[r[i]-r[i+S],{i,S}]
pot1[r_] = dipole.r/magnitude[r]-3
pot2[r_] = pot1[r] + 1/2/magnitude[r]-S * r.qsum.r
.......+'h=I t::. n"\.
r, .... A. _n~~-= r.r __ ... ~ r. ......1 ....,..+'lr.......+'h1 ....,..+r.......+'h1"\. I _') 'l"\.
... 'r
r .& ...~ " l "

~
-
,... .................'r, -~ -~
'J --.o;rT 'T "'-'T

FrameLabel -> {1{.6,y.0}1,lpotential"},


PlotStyle -> {Dashing[{.01 . 01}],
Dashing[{.03,.03}],Dashing[{1.0,0}]}]

Needs["Graphics"PlotField II]
efield=-{D[pot[{x,y.O}],x],D[pot[{x,y.O}],y]}
direct ion=ef ield/magnitude [efield]
n1nT~=P1 ....1i1ril; '1 on ..(x 10 10)...fv -10 10).
P1 ....
~

-~~nl
E. Program Listings 255

1.

Print [1I\n Line Integrals \n ll ]


rl={Cos[2Pi t],Sin[2Pi t],t}
r2={1,O,t}

va ua e r , ,
DisplayFunction->Identity]
p2:=ParametricPlot3D[Evaluate[r2],{t,O,1},
Dis layFunction->Identit ]
3:=ParametricPlot3D[Evaluate[r3] {t
D's la Funct'o ->
1}

plotl:=Show[pl,p2,p3,PlotLabel->1I Line integrals ll ,


AxesLabel->{lI x ll,lI y ll,lI z ll},
DisplayFunction->$DisplayFunction]

v [r_] :=D [r, t]


int[r_]:=Integrate[f[r].v[r],{t,O,l}]
r4=t{x, ,z}
curl[{fx f fz

D[fy,x]-D[fx,y] }

Construction for the van der Waals Gas \n ll ]

Join[sol[[l]],{Rule[p,pc]}]

eq3 = p[vl]==p[v3]
eq4 = p[vl]*(v3-vl)==Integrate[p[v],{v,vl,v3}]
On[Integrate::gener]

.34,5.},

vmin = v I. FindMinimum[ p[v], {v,O.4}] [[2]];


vmax = v I. FindMinimum[-p[v], {v,1.}][[2]];
vtest = (vmin + vmax)/2
256 Eo Program Listings

.
P1ot[{pmax[v],p[v]},{v,O.34,5.},
,
P1otRange-){{O,5},{O,2}},
Frame -) True, FrameLabe1 -) {II V I l , II p ll} ]]]

1.9 Best Game Strategy: game.c

2.1 Quantum Oscillator: quantumo.m


Print[lI\n Quantum Oscillator \n ll ]
["_,k_]:= S rt[("+k+l)]/2 Ii Abs[O-k]==l
q[j_,k_]:= Ii Abs[j-k]!= 1
q[n_]:= Tab1e[q[j,k], {j,O,n-l}, {k,O,n-l}]
hO[n_]:= Diagona1Matrix[Tab1e[i+1/2,{i,O,n-l}]]

Frame -) True,
FrameTicks -) {Automatic,
Tab1e[{O.5*j.If[EvenQ[j],ToString[j/2],III1]},{j,19}]},
FrameLabe1 -) {"lambda",lI ener yll},
P1otLabe1 -)IIEigenva1ues of h[4]11 ]

evnum[n_,la_]:= Sort [Eigenvalues [N[h[n]/. 1ambda-)la]]]

P10tRange -) All,
FrameLabe1 -) {"l/n",IIEO(n)"},
P1otSty1e -) PointSize[O.02],
Disp1ayFunction -) dentity
gr2 = Graphics[{Thickness[O.OOl],
Line[{{1/20,O.559146327},
{1/7 ,O.559146327}}]}]i

. " , , ,-
ev2[k_]:=Tab1e[{ev1ist[[i,1]],ev1ist[[i,2,k]]},
{i,Length[ev1ist]}]
p1ot3:= ( Tab1e[gr[k]=ListP1ot[ev2[k],P1otJoined ->True,
1SP ay unct10n -) ent1ty,
Frame -) True,
FrameLabe1 -) {1I1ambda","energyll}.
FrameTicks -) {Automatic,
*"

Disp1ayFunction -) $Disp1ayFunction] )
E. Program Listings 257

Print["\n Electric Circuits \n"]


eql={vr+vo==l,ir==ic+il,vr==ir r,
vo==ic/(I omega c),vo==I omega IiI}

numvalue = {c -> N[10 (-6)], I -> N[10 (-3)]}


A A

vosnum = vos I. numvalue


flist=Table[vosnum l.r->100.0*3 s, {s,O,3}]
A

p 0 0 va ua e s 1S , omega,
PlotRange-> 0,1 , Frame -> True,
FrameLabel -> {"omega","Abs[vo]"},
FrameTicks -> {{20000,30000,40000},Automatic} ]

FrameLabel -> {"omega","Phase(vo)"},


FrameTicks -> {{20000,30000,40000},Automatic} ]

vsaw - +
omegares= Sqrt 1 c . numvalue N
alist=Table[N[vsaw[(n-l)/256 T]],{n,256}]
blist=InverseFourier[alist]
plot3[fac_,w_]:=Block[{volist,vtrans,omegai,plotlist},
. *
Table[vosnum/.{omega->omegai*(s-l),r->w},
{s,128}],{0.0},
Table[vosnum/.{omega->omegai*(s-128),r->w},

PlotRange -> All]]

eq2={ir(r + 1/(1 omega c) + Iomega 1) + vo ==1,

so

PlotRange->AII,Frame -> True,


PlotStyle->{Thickness[0.006],Dashing[{.01,.008}],
Thickness [0.003]},
,
omega ,

plot5:=Plot [(power/.numvalue)/.r->10.0,{omega, 10000,700OO},


258 E. Program Listings
D1 ..... +D~-- ..... _~A11 - .~ T,..na

.-
~ -'::1._ _.. . .r.r
.... i t\t\t\t\
' -,-
-
' ...
l-

Automatic},
FrameLabel ->{lIomega","P/PO"}]

-
~.'l
_. .
n!:UT1l
-- ...
V.au.a
. .. . III

Print["\n Oscillator Chain \n II]


matl = { { 2f , -f , 0 , -f*Exp [-I q] },
{ -f , 2f , -f , 0 },
.( 0 -f . 2f . -f }.
{ -f*Exp[I q] , 0 , -f , 2f } }
massmat=DiagonalMatrix[{ml,ml,ml,m2}]
mat2=Inverse[massmat].matl
- , -J.a.U.&.CL"\.,A"
... r r
....
",nopLr..l.geDv -
P P

L
mat2/.{f -> 1., ml -> 0.4, m2 -> 1.0, q-> x}]]},
{x,-Pi,Pi,Pi/50}]
lotlist=N[Flatten[Table[
Ma[{# [[1]] ,Sart [#[ [2,k]]] }It,
eivenlistl.{k.4}] 1]]
plotl := ListPlot[plotlist,FrameLabel -> {"q",lIomega"},
Frame -> True,Axes -> None,
FrameTicks ->{{{-Pi,"-Pi"},{-Pi/2,"-Pi/2"},
r,..
l.V,
",.."" rn."'" lin.' , ... "" rn.' lin..: ",,- "-
v J , V . , ... , . . . ,... J , \''' . , . . . J J ,
, ." '\
- ..-oJ

eigensys := Thread [Chop [Eigensystem [mat2 I.


{f -> 1., ml -> 0.4, m2 -> 1.0, q->O.O}]]]

2.4 Hofstadter Hutterl1y: holstadt.c

1***** Hofstadter Butterfly *****1


~. h,>
:ft; ... ,.lnl'1 ... _'L

*~ __, .. ...1_ -... ',;,.." 'h~


&

#define QMAX 400


#define SHIFT 1

mainU
{
int gcd( int , int);
int ie, n, nold, m, p, q, x;
1'1,.... },.1 ... "l.;onUl
- ... -
n;
.- a nl::.;n1t'1
.-
.
nl::.;
& .nl::.; ... av
.:_ ...
.&&U
_..1_':
0 ...... - ' ...
-
~

char str [tOO] ;

initgraph(ltgdriver,ltgmode,"\\tc")i
settextstyJ.eU,U,l.);se'tcoJ.orlIU:;U);
outtextxy{SHIFT+l00 ,::>HJ.l'--1'+QMAX+l0, "Hors'tad'ter tiu't'terrJ.y') i
settextstyle(O,O,l)jsetcolor(WHITE);
outtextxy(SHIFT+l00,SHIFT+QMAX+60,"Commands: eXit,arbitrary");
E. Program Listings 259

r- - ---, .... ,.I of \.

/* the eigenvalues for q=2 are known


and have to be dravn separately */
setvievport(SHIFT.SHIFT.SHIFT+QMAX.SHIFT+QMAX.1);
putpixel(0.5*QMAX.(0.5+sqrt(2.)/4.)*QMAX.WHITE);
putpixel(0.5*QMAX.(0.5-sqrt(2.)/4.)*QMAX.WHITE);

for(q = 4; q < QMAX ; q+=2)


.[
,
I. .
.. , ..
II -'/...111 .\
.
.. y ...... 40- v ... , .. v .... "'1 to.....
...''''1'' ,. ........ . ,. ,.,. .,
;,e,-v
.. '-\';'U.l.r.a. ..,nAA -..Lv.,;,u.l.r.a..,;,u.l.r.a. -",llAA--..L..LV.';'U.l.r.a. -IoV ..L/,

clearvievport();
outtextxy(1.10.str);
setvievport(SHIFT.SHIFT,SHIFT+QMAX,SHIFT+QMAX,1);

for(p = l', P < q; p+=2)


{
if ( gcd(p,q1) continue;
_.:_~ _ (" n .....: .... \/_.
... ,- _. r - .r ' , , .
, ... - "v ,
....v ......
~ ,.
..LV..L\.I.e
,.
- v .I.e "'
..... , .....
........ ~ , .I.e -,,
{
e = 8.0*ie/QMAX - 4.0 - 4.0/QMAX ;
n = 0;
psiold = 1.0; psi = 2.0*cos(sigma) - e;
if( psiold*psi < 0.0 ) n++ ;

for( m = 2; m < q/2; m++ )


.(
...

C.~I
~ . . . . . . . . y~ - ( 'l
. ...
~ "
, (~ ..
,,~ ...
.\
., .... \ .... ..
r
~ _
.
... ~ .. ,.1~

...... , r , . v.v,
-

40-

psiold = psi; psi = psinev;


}

psiold = 1.0; psi = 2.0 - e;


if( psiold*psi < 0.0 ) n++ ;
psinev = ( 2.0*cos(sigma) - e )*psi - 2.0*psiold;
if( psi*psinev < 0.0) n++;
.
nc.; ... l...J = nc.; nco; = nc.;nAU
c c .
~
.Lv... ,
I
au
_ n
~, au ,
. 'if'n ~, au ,"
{
psinev = ( 2.0*cos(sigma*m) - e )*psi - psiold;
if( psi*psinev < 0.0) n++;
psiold = psi; psi = psinev;
}
psinev = ( 2.0*cos(sigma*q/2) - e )*psi - 2.0*psiold;
if( psi*psinev < 0.0) n++;
y,.. .... nVAY I (.,:1,. ... +\,.
'~f~
...... '40-
'" ..... ,...1\
4O-V_ ..... , 0;
.... ., -:.'
, ... , ... v, ,
0;

nold = n;
260 E. Program Listings

., "1_._
1..
,I ... -- ---r
': __ 1

/* p-loop */
};
if (kbhitO) {str[O]=getch();getch();if(str[O]=='e') break;}
l' 1* q-J.oop *1
closegraph();
} /* main */

;..,1- lI'''.-I ( ;..,1- Jll ;..,1- h'\


Q

.r.
if( b==O) return a;
return gcd(b,a%b);
}

2.5 Hubbard Model: hubbard.m


Print ['I\n Hubbard model \n"]
s1tes=lnputL" Number of s1tes: "J ; Pr1ntL""J
particles=Input["Number of particles: "]; Print [1111]
spinup=Input[IIHov many of them are spin-up particles? II]; Print [1111]
spindovn=particles - spinup
tkin=-2.*t*(Sum[N[Cos[2*Pi/sites k]],
llr -~'nn.... r( -1'\ /.,1 ~, nn.... r,
. . I'll '\1 ~
C'
... r".D~
_rvr,,__
.- ... -.1_'::' __ ...... ,
1.11'

{k,-Floor[(spindovn-1)/2],Floor[spindovn/2]}])
Print [II II]
Print[1l The ground state energy for U = 0 is: II , tkin]
.le:It = t'ermutat1onsl TaD.lel l.:IL J <= sp1nup, 1, UJ,
tj,sitesJJ J
right = Permutations[ Table[ If[ j <= spindovn, 1, 0],
{j,sites}] ]
index = Flatten[ Table[ {left[[i]],right[[j]]},
.fi .T, ... rlAf1:1l f;T, ... rT;rJ'h1:1l 1 11
.....,.-1 = T .. r ..
.'L
., .
.'L
...
... "1
plus [k_,sigma_] [arg_]:= ReplacePart[arg,l,{sigma,k}]
minus [k_,sigma_] [arg_]:= ReplacePart[arg,O,{sigma,k}]
sign [k_,sigma_, arg_] := (-1)-(spinup*(sigma-1*
~-1) ~::iuml argLLs1gma,JJJ,'tJ,.lt-l1'J)
cdagger[sites+1,sigma_] Lany_J : = cdagger [1 , sigma] [any]
c[sites+1,sigma_] [any_] := c[1,sigma] [any]
cdagger[k_,sigma_] [0]:= 0
c[k_,sigma_] [0]:= 0
.. ...... r'k' ~; O'm::\ 1 r'" ~ r::\TrJ' 11=
...-
4l, ( 1 _ ......,... r r... .; ......... 1.. 1 1 ,
'O~ ...

sign[k, sigma,arg] *z[plus [k,sigma] [arg]]


c[k_,sigma_] [factor_. z[arg_]] :=
factor*arg[[sigma,k]]*
_. ~ -
s1gnLK,s1gma,argJ"'ZLm1nusLK,s1gmaJLargJJ
_.

n l.lt_, s1gma_J LUJ : = U


nLk_,sigma_JLfactor_. zLarg_JJ:= factor*arglLsigma,k]]*z[arg]
scalarproduct[a_,O] := 0
E. Program Listings 261

-, -
,
scalarproduct[z[arg1_],factor_. z[arg2_]]:=
factor* If[arg1==arg2,1,O]
H[vector_] = Expand[
-t*Sum[cda er[k,si a] [c[k+1,si a] [vector]] +
cdagger[k+1,sigma][c[k,sigma][vector]] ,
{k,sites},{sigma,2} ] +
u*Sum[n[k,1][n[k,2][vector]] ,{k,sites}] ]
II

,
II X II ,end,". II]
h = { hlist = Table[H[z[index[[j]]]], {j, end}];
Table[ scalarproduct[ z[index[[i]]], hlist[[j]] ],
i,end, j,end])

Print[lI\n Calculating the energy eigenvalues."]


state = Chop[Table[Flatten[

Print[1I \n Commands: II]


menu: ={Print [1I\n
menu => This menu \n\n
new => estart t e program n n
plot1 => Multiparticle spectrum as a function of U/t n n
plot2 => Double occupancy in the ground state \n
as a function of U/t \n\n

menu

h/.{t -> 1.0,u -> uu}]]]] [[1,2]]]


sJ.tes

plot2:= -> 1.0, u -> 1.0}]];

enerate!"

Axes -> None, Frame -> True, FrameLabel->


262 E. Program Listings

'[IITT/t- 1I lIinn'h1 ...


. , ..... 11 ...... v ... 1"1~1 )
"
plot3:= (groundstate = Map[{#[[1]],#[[2]]/sites}i,state];
g1 = ListPlot[groundstate,Frame->True,Axes->None,
PlotStyle->PointSize[O],PlotJoined->True,
l'"rameLabe.l->1."u/t ,"linergy per s1te/t"},
DisplayFunction -> Identity J;
f [u_ ,0] = 1/4 ;
f [u_ ,0. 0] = 0.25 , .
fru x 1 = BesselJ ro xl *BesselJ rt xl/(x*l1+Exnrx u/21))'
.nlnt:l;~t: = TJOlhlAr.fn -40*
g2 = ListPlot[plotlist,
.. ~

u
r~r ......1
~. ~. , "~ ,~. .,
f .... n s::: s:::')1.11. f n
"I ~ 1 .~. , , ~ ,. ')1.1
-" .. ,

PlotJoined -> True,DisplayFunction -> Identity,


PlotStyle -> Dashing[{0.01,0.01}]];
-
OlnowLgl, g", U1Sp.1ayruncl;1on -7 i)U1Sp.1ayruncl;10nJ }

3.1 Population Dynamics: logmap.c

1***** Population dynamics *****1


#include <stdlib.h>
#include <graphics.h>
#include <math.h>

..... v ........................" ,

main()
{
void channel{double);
int gdriver=DETECT,gmode;
char ch,str[100];
double xit=0.4,rmin=.88,r;
int x,y=50,i.ir;

............
..: ...: , 11\ \ 'V_
II. . ...lI_": .... _
... '-0-- .... --, ....-
-
... II'" .
4. ....

maxx=getmaxx();
maxy=getmaxy();
setcolor(RED);
settextstyle{1.0,1);
outtextxy(100,maxy-80,1I Lop:istic map x=4*r*x*(1-x)II);
settextstyle(O,O,1);setcolor(WHITE);
outtextxy(50.maxy-30,
II Commands: lower,higher,refresh,print r,channel,arb.,exit II) ;
"' ..+u;
- _.
_ .. 1
,_.
(1 1 """"vv "",,"vu_1nn i ) .
. /1 _ _ ..: _, ..... / / ___ _1 ;"1\,
. .
J' '--J ---"

while(1)
{
X1t=4.*r*x1t*\1.-x1t);
x=xit*maxx;
putpixel(x,y,WHITE);
if(kbhitO)
E. Program Listings 263
r
_ . ...: 1. ( -'- ( \ \
- - - - - '0' " ,
{
case ' l' : if (ymaxy-100 y+=1;break;
case ' h' : if(y>1) y-=1;break;
default : getch {) ; break;
case ' e' : closegraph 0 ; exit(1);
case ' c' : channel(r);break;
case 'p' : sprintf(str,1I r= Y.lfll,r);
'(1 ,v
w
str)'
'h"''''J:lllr..
' .... , . ... ,~ ....... .,~
..... "''''' -(" \ ,.'- , . .1

} /* switch */
r=1.-(1.-rmin)*y/(maxy-100);
for(i=0;i<100;i++) xit=4.*r*xit*(1.-xit);
1 I . 1r *1
Jo/* wh11e *1
}/* main */

void channell double r)


l
~~......,"" .... ~.= A."
int x,y[1000],i;
clearviewport();
for (i=O;i<maxx;i++) y[i] =0;
~1ne\V,maxY-lvv,maxx,maxY-lVV);

whilel !kbh1t{))
{
xit=4.*r*xit*(1.-xit);
x=xit*maxx'
vrxl++
~ . ., , _._-
,..."t-,...;v",1 (v ..... vv_1nn,.,.,rvl WI-II "Ia" .
}
getch();getch();clearviewport();return;
}

3.1 Population Dynamics: logmap.m


Print [1I\n Logistic Map \n ll ]
I lX_J =4 r XlI-X)
1terfLn_J:=NestLf,x,nJ
plot1:=Plot[Evaluate[{x,f[x],iterf[2],iterf[4]}/.r->.87],
{x,0,1}, Frame -> True,
PlotStyle -> {{Thickness[0.002],GrayLevel[0]},
.(Thi _. ,roOO21

""--
{Thickness[0.002],GrayLevel[.6]},
.
n .. C!h; ...... rrn nn':l n nn':ll.ll.
-~-- .
{Thickness[0.002],GrayLevel[0]}},
FrameLabel -> {II XII , II f [f [f [f [x] ] ] ] II} ]

nr lX_ , r _J =N lr lXJ J
11stlLr_,n_J:=NestListLnfL#,rJ&,.65,nJ
plot2:= (list=list1[.87,40];
264 E. Program Listings
... _... ,W'" ~ r, . W'"
- ..-
W" .... r", "'''',
0' ,,,..- ... v" L...... ~"'..- ... v" .. ,,] ......
. .
"

-" h.y
.J;
'LV. V-'.J ,

. "
g2=ListPlot[list,PlotJoined->True,
PlotStyle -> {Thickness[O.OO2),GrayLevel[.7)},
FrameLabel -> {t1n",t1 x (n)"},
DisplayFunction -> Identity);
Shov[g2, g1, Frame -> True,
DisplayFunction -> $DisplayFunction) )
.r. .l"'... '::tr....
_. - n "'.... "1.1 .=(...1=Pl",... r... ~r,..
-- ...1 rv n 1'\.
... _. ,. .... ,T .....,. ,
.;..~--, -' '. '- -' - .,
.+
..
AA' -~.... ~"
r, ~ r:' . ; oIL
LU.L L1I',.L.J"', V.
'"
oJ, oJvV.J ,
..... "'''',
'VJJ'

lil=NestList[{nf[#[[1]),r],nf[#[[2]],r]}l,
{xx,nf[xx,r)},1000);
li2 = Flatten[Map[{{#[[1]],#[[2]]},
{#[[2)),#[[2))}}l,lil),1);
li3=Flatten[Map[{{#[(1)),#[[2)]}}l,li1],1];
g2=ListPlot[li3,PlotRange -> {{O,1},{O,1}},
PlotStyle -> PointSize[O.015],
n;"'.....l .... .;",... _'> T,'" 1 ,

_':J_T ..:
0
_+n,_ _
"'+v r, . : '1" n,"
.. _ _ _ , .

.... , . .
__ ...
... .... - -. ..- -....
_.... .r.rn 11. .r~" 1 ~ ~
, , , ,
..... v
.-
, "', ...........
,
PlotStyle -> Thickness[O),
DisplayFunction -> Identity ) ;
g4=Graphics [Text [
StringJoin[t1r = ",ToString[r]],{O.5,O.05})];
g5=Graphics[Line[{{O,O},{1,1}}]);
Shov[g1,g2,g3,g4,g5,PlotRange -> {{O,1},{O,1}},
AspectRatio -> Automatic,
... -'> T....,.... .
n..: __, _ ... _.... cl.>n..: ._, _ ...
. "
'",-
. "
.1\
,

h[x_)=97/25 x(1-x)
hl[n_]:=NestList[h,N[1/3),n]
hl[n_,prec_]:=NestList[h,N[1/3,prec),n)
tab:=TableLtprec,PrecisionLLastLhlL100,precJJJ},
{prec, 16, 10O})
plot4:=ListPlot[tab, Frame -> True,
PlotStyle -> PointSize[O.01),
-.r"D__
",h... l -'>

.. - "~_~,,,_ ",-4'
._-___ ,_ , .......
.- ......+1. __ "
,
II.
.:/
~
" ............................. ., "" .I J

period[1)={c,1}
accuracy=30
mUl.t=30
period[n_]:=period[n]=Join[period[n-1],
correct [period [n-l)))
correct[list_):=Block[{sum=O,li=list,l=Length[list)},
Dorsum+=lirHll ..fi2 .Ill
Ti'rnrltUH... .,ml H rr1l1=o . 1; rr1l1~1l
,- .- '- .
g[n_,mu_):=Block[{x=Sqrt[mu),l=Length[period[n))},
--
1 .. 1
E. Program Listings 265

n.... rv=C!.......+r_.. ~(_1\-( .....................Ir...l rr.......


~. &-~-

..... , ..., , .... ,


1' . '::I
.. , .....
_1I'L'
~~
_~r
ll\ vl
~~'
-.. .
fr[n_] :=fr[n] =(find=FindRoot [g [n,mu] ==mu,{mu, {15/10, 16/10}},
AccuracyGoal->accuracy,
WorkingPrecision->accuracy,
Maxlterat1ons->max1tJ;
mu/.find)
rr [n_] : = rr [n] = (1+Sqrt[1+4*fr[n]])/4
delta[1]:= Print[" The value of n is too small"]
deltar21:= Printr" The value of n is too small"l
~Al+'Sllrn 1= ~Al+'Sllrnl=(~n,.+.r1 .. ~ ,rn-1l1-~n,.+.r1 ... 4*~,.rn ?ll'/
(C!:'....+r1
&.
.. ~. r...ll
- .C!........:r....
&-
~, r....111\
~' . , ~. .... ~. ~. ....
feigenbaum :=
Do [Print [" n = ",n,
" Feigenbaum constant = ",delta[n]] ,{n,3, 1O}]

3.2 Frenkel-Kontorova Model: frenkel.c


/***** Frenkel-Kontorova Model *****/
#include <conio.h>
#include <math.h>
#include <stdlib.h>
#include <graphics.h>
_ ....... f\
"
..
r

int gdriver=DETECT,gmode;
int xs,ys,color=WHITE,maxx,maxy;
long nsum=O;
double k=1.,sig=.4,p=O.5,x=O.55,pi=M_PI,xnev,pnev,h=O.,vind=O.,
xold,pold;
char ch,str[1000];

initgraph(lgdriver,lgmode,"\\tc");
- -
O'
,f\. ,
'\
~"""'J6-V~"""'J'"

settextstyle(1,O,1);setcolor(RED);
outtextxy(150,maxy-80,"Frenkel-Kontorova Model");
settextstyle(O,O,1);setcolor(WHITE);
outtextxy(100,maxy-35,
"Commands: exit, print, nev start, clear, arbitrary");
xold=x; pold=p;
vhile(1)
{
n..... u=n~1r/') In;*",; ... (') *n;*v\' .
_.0__ -r.o--.._,

xs=fmod(xnev+100000.,1.)*maxx+1;
ys=(1.-fmod(pnev+100.,1.*(maxy-100)+1;
putpixel(xs,ys,color);
V1n<1+=xnev-x;
x=xnev; p=pnev;
h+=k/4./pi/pi*(1.-cos(2.*pi*x+(p-sig)*(p-sig)/2.;
nsum++;
266 E. Program Listings

{ sWitch(getch(
{
case 'e'
case n

case
II II


setviewport(10,maxy-20.maxx,maxy,l);
clearviewport();
outtextxy(l,l,str);
se V1ewpor , ,maxx,maxy,
case c setv1ewport, ,maxx,maxy-
clearviewport 0 ;
setviewport(l,l,maxx,maxy,l);break;
etch . break .

}/* while *1
}/* main *1

Print[" \n Frenkel-Kontorova Model \n"]


pi = N[Pi]

s1gma=.
nmax=1000
t[{x_,p_}] = {x + p + k/(2 pi) Sin[2 pi x],
p + k/(2 pi) Sin[2 pi x] }

tab=Table [{xl [[m]] ,kl (2 pi) ~2*(1-Cos[2 pi xl[[m]]])}.


{m,ll}] ;
pl=ListPlot[tab, PlotStyle -) PointSize[O.03],
E. Program Listings 267

plot3[xO_:.06,pO_:.34]:=
(xl=Map[First, NestList[t, {xO,pO}, 99]];

wind[xO_:.0838,pO_]:=(w1=xlist[xO,pO]j
(w1[[-1]]-w1[[1]])/nmax )
hpO:=Table[{pO,h[.0838,pO]},{pO, .2, .4, .01}]
p 0 is 0 p, rame-
rame a e - p , energy ,
PlotStyle -> PointSize[O.013]]
hxO:=Table[{x,h[x,.336]},{x,.15,.2,.001}]

PlotStyle -> PointSize[O.013]]

a Ice: slerp.c
***** Fractal Lattice *****
#include <graphics.h>
#include <stdlib.h>

main 0
{

" .
getch()j setcolor(WHITE)j

while ( !kbhitO)
268 E. Program Listings

'\ . . VA 1 (nt:
' . Y.
.nt: .v. WH Tto: J

getch();getch();
closegraph();
}

3.3 Fractal Lattice: sierp.m


Print[lI\n Generates and Plots a Sierpinski Gasket \n"]
list={{{O.,O.},{.5,N[Sqrt[3/4]]},{1.,O.}}}
mult[d_]:=Block[ {d1.d2,d3},
d1={d[ [1]] , (d[[2]]+d[[1]]) *.5, (d[ [3]] +d[[1]]) *. 5};
d2=d1+Table[(d1[[3]]-d1[[1]]),{3}];
d3=d1+Table[(d1[[2]]-d1[[1]]),{3}];
, . .- .... , .'.rr,,.,.
. --,--,--.1
.T..:J1 ..:Jt'J

.,
,\,.&...i> .. ~ ,y.&.u
..:J":2'\.

.,.
1
J
."1
,
~

list2=Map[mult,list];
list=Flatten[list2,1];
plotlist=Map[Polygon,list];
Show[Graphics[plotlist],
ASDectRatio -> Automatic]]

3.4 Neural Network: nn.c and nnf.c

~Ul.. '"' ~i:)


. !1 . L 1 n"n.
Viol. '-I.LJ-
TlA'Il.. .1.
VUJ.'y'

/***** Neural Network - Reading from a File *****/

IFl.nC.LUQe ~Sl;Q.Ll.D.n,;>
JJl.nclu<1e <math.h>
'include <string.h>
#include <stdio.h>
~.
.... ..:1
N 10
~.
.... ..:1
2 20

float runs=O,correct=O;
p"
main \inl; argc, cnar argv LJ J
1..
int neuron[N2J,l.nput,i;
float weight[N2],h,wsum,kappa=1.;
char ch,str[100];
FILE * fn'
.
if (argc==1)
{
printf(" Input file name? II) ;
SCanJ: \ ""f:> , S...r J ,
.t
else strcpylstr,argvLIJJ;
if ( (fp=fopen (str, "r ll ==NULL)
E. Program Listings 269

r,
~
,
exit(1)j
~ III
...........
'1:'," OJ
0" ~..,
~
.....
"I
..,~"'.
II
........ , ..
.\

}
printf(1I File Yes is being processed lI. s tr)j

for(i=Oji<N2;i++) { neuron[i]=1j veight [i] =(float) i/N j }

vhile (feof (fp)==NULL)


.(
ClU; -t:,.l\ (~"'6+" (4n) )
~~ -&

r.
case ' 1' : input=1j runs++jbreakj
case ' 0' : input=-1j runs++;breakj
default continuej .
.t
for(h=O . i=O ji<N ;i++) h+=veightlij*neuronlij;
for(vsum=O . i=Oj i<Nj i++) vsum+=veight[i]*veight[i]j
if(h*input>O.) correct++j
;~( l\*;nnnt: < *Cln.,.t: (IolClnm) )

-
.,: ......(;.. n.; LW . ; .&-~ , u':; ...,..},.+ r;,.&-= -
.- , - -
.
4' __ f..: _1>1'1_-4 ..: ..... n
- , -, ~
..: __ ,
1- ,
r;, /(41 ... ",-t:)W .
---_.- -..-..-- ---_.- ..- -...
r..:1_ r..: _-4 1
-~ .
neuron[O]=inputj
}
if(runs!=O)
prl.n'tIl"'\n 7.tl.VI Va~l.C1 l.npu'ts"'.runsJ;
prl.ntf(lI\n 7.6.2f 7.7. predl.cted correctlyll.correct/runs*lOO.);
fclose(fp)j
getchO j
}

4.1 Runge-Kutta Method: rungek.m


Print[lI\n Runge-Kutta: Pendulum \n ll ]
K'- r~ V vn tit:_'=
~ v:.. . -
" i: r r1,.~ lrl) lr~ lr4 1. . . .
k1 = dt N[ fl. Thread[y -> yp] ] j
k2 = dt N[ f I. Thread[y -> yp + k1/2] ] j
k3 = dt N[ f I. Thread[y -> yp + k2/2] ] j
.lt~ = C1't 111 L I I .J.QreaC1 Ly '~ yp + .It,jJ J j
yp + (kl + 2 k2 + 2 k3 + k4)/6 j
RungeK[f_List. y_List. yO_List. {x_. dx_}] :=
NestList[RKStep[f.y.#.N[dx]]&.N[yO].Round[N[x/dx]] ] Ij
Length[f] == Length [y] == Length[yO]
);",,1 r.,: ,r ,rn },. ,.= ,rn .&- },. wr.,: /
1'0
.. ru -~ "r--
un" _0-

Euler[f_.y_,yO_.{x_.dx_}]:=
"r --
.. _. -." -. ,,_r -. -- -"
NestList[EulerStep[f. y. #. N[dx]]&, N[yO] Round[N[x/dx]]
]
naml..1l;On = p ~/~ \;OS -
LqJ
tmax = :lUU
dt - 0.1
phiO = Pi/2
270 E. Program Listings
1'\ _ 1'\
I'v v
~ ~-
L' - v.vo
phase:=RungeK[{D[hamilton,p],-D[hamilton,q]},
{q, p}, {phiO,pO}, {10,dt}]
plot1:=ListPlot[phase,PlotJoined->True,Frame -> True,
AspectRatio->Automatic,
FrameLabel -> {"q","p"},
RotateLabel -> False,
PlotRange -> {{-2.3,2.3},{-1.85,1.85}}]
.. . r f. .~. r ..' .'\.
.....
.... _ft . YI

r .... 'L "I' , r .....


..
r""
r . ~ ...... r
"l.'i,'pJ,"l.'pULV,'pV.T,"l.,"~,U,".TJ

plot2:= ListPlot[phase2,PlotJoined->True, PlotRange - > All,


AspectRatio->Automatic,Frame -> True,
FrameLabel -> {"q","p"},
RotateLabel -> False,
PlotStyle -> Thickness[O.OO3] ]

phase3:= Euler[{D[hamilton, pl, -D[hamilton, q]},


f_ _'\. J_l..":1'\ _I'\'l.. J11'\ ...1.'l..1
. .. - 'I' .n..
"VA __ ~ 1"'.
.."
_ ....
1'''''
. ..
,A
"1'---' 1'-'"
n.. ~ 'Y' ...
.. --, --.....
....... .. .......
, ......... ,
.
__ V
I'... u .......
-
,. .......... , . . . . U&II...

'r "' 60_ ,


FrameLabel -> {"q","p"},
RotateLabel -> False,
PlotRange -> {{-2.3,2.3},{-1.85,1.85}}]

4.2 Chaotic Pendulum: pendulum.c


/ ..... Chaotic Pendulum ..... /
"'i"... "1nA1: ttnllhl ...
.a ...

'include <graphics.h>
'include <stdlib.h>
'include <math.h>
*inc.Luue ....sl<uio.Jl....
JF1nCJ.uae \~C\reC1peS\nr.n'
'include "\tc\recipes\nrutil.h"
'include "\tc\recipes\nrutil.c"
'include "\tc\recioes\odeint.c"
:1:;" ... 1,,11... lI\tr-\
.. :\rlrae e"
*; ...... 1,,11 ... 11\+ ... \
.. ,\.. . 1r4 ..."
double dt=.1,r=.25,a=.5,pi,ysc=3.;
int poincare=O,done=O;
in~ maxx,maxy,ximage,yiWA~e;
vo1<1 pr1nt(.),<1er1vs(.<10uDJ.e,<10uDJ.e.,<10uDJ.e.),event(.<10uDJ.e.J;

main()
{
int adriver=DETECT,Q'Dlode'
;"1: i "nw "hAtt Ynlttvnltt Y"iRV V"AV'
" "
double y[3],f[3],t=O.,eps=1e-08;
E. Program Listings 271

..........0 .. -r
10. ..J
-o,;~
.
.. ..... , ...
. , " .... ,..,,'\
,,\ \
., "
.
WGAA-'!lO:; .\ / ,

maxy=getmaxy()j
ximage=maxx-20j
yimage=maxy-110j
pi=acos(-1.)j

y [1] =pi/2. j
y[2]=O. j
.. . f\
.
_. ... ,,,
\,",u.u.o:;--u/ ,,'
{
if (kbhit 0 ) event(y)j
if (poincare==1)
{
odeint(y,2,t,t+3.*pi,eps,dt,O.,inok,inbad,derivs,rkqc)j
xold=fmod(y[1]/2./pi +100.5,1.)*ximagej
yold=y[2]/ysc*yimage/2+yimage/2j
., . . (.. . ,,'~ , '.1 ,,'~ ....... ,~.&. .......
-g' " ".1 ._'
,~.&. . .,\.,
_ .L~ .....
.., .. .. ..... r" ,
J
else
{
xold=fmod(y[1]/2./pi +100.5,1.)*ximagej
yold=y[2]/ysc*yimage/2+yimage/2j
odeint(y,2,t,t+dt,eps,dt,O.,inok,inbad,derivs,rkqc)j
xnev=fmod(y[1]/2./pi +100.5,1.)*ximagej
ynev=y[2]/ysc*yimage/2+yimage/2j
;i'(anl:l(vn""u-vnlt1"
+=+.&.~+
.
. - I?) l;n",,(vnlt1 vnlt1 vn""u vn""u)'
'J ,

.
1..

}
closegraph()j
}

void event (double y [] )


{
svitch (getch(
.(
~ ............ =... '- ...
..
,. ... e .... 1 .... 1. ,

"

I I 1'\ . '
... _..... .... 1'''' ......... " , ,
default: getch()jbreakj
case I i I : a=a+.01jprint()jbreakj
case 'd ': a=a-.01jprint()jbreakj
case I + I : ysc=ysc/2. jprint() jbreakj
case '-' : ysc=ysc*2.jprint()jbreakj
case I s I : y[1]=pi/2.jy[2]=O.jprint()jbreakj
case 't ': poincare=!poincarejprint()jbreakj
'~~ 4? "#11='1")' . "(1~ 4 40 4)
.'..
c:asl'! I,.. I

.
~(lI'Ji~lI ''''.\ ........, ... +(\
~ .

.l.
}
272 E. Program Listings

....... .;~ ~ __.; .... (~


, .......l.' . . . + ~ ....... l.'_ ..... ~ .......l., ........ .&\
-,
J
{
f [1] =y[2] ;
f[2]=-r*y[2]-sin(y[1])+a*cos(2./3.*t);
r
void print (void)
{
char strin~r1001'
~ ...1:v; .... (1 1 .m~YY .m~Yv 1)
,.1 ......_.; .. n . "
...
settextstyle(1,O,1); setcolor(RED);
outtextxy(40,yimage+30,"Forced Pendulum");
settextstyle(O,O,1); setcolor(WHITE);
outtextxY~lu,Y1mage+/u,
Commands: exit,increase a,decrease a,start,read a"
II

".+,-.toggle,clear,arbitrary");
setcolor(LIGHTGREEN);
rectangle (9 9 ximage+11 vimage+11l'
.l~,.. - -
.. p<_,; ... +oF(
.r
IIIH I ....

...
...="'1 oF II ....
II .. ="'1 oF
.. ...
,.
if(poincare==l) sprintf(lstring[strlen(string)]," - Poincare");
outtextxy(320,yimage+40,string);
setviewport(10,10,ximage+l0,yimage+l0,1);
;

4.3 Stationary States: schroed.c

1***** ~CnrOeQ1nger ~qua~1on 'I

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
1t; 'nrlnrl... <m~1:h. h>

double e=.5,a=O.1;

maine)
1.
v01d 1mage(vo1d), pr1ntl double.double,double );
double k(double),step(double *x,double dx,double*y,double*yml);
int gdriver=DETECT,gmode;
int xs,ysnew,ysold;
rlnnhl ... rly=10 I~OO 0 . =10 I~oo v vm1 "vn1 -'
=.O~
..
.
~ ...= nE;: 'V' 'V'P<1 vm1
-r
" "
..
initgraph(lgdriver,lgmode,"\\tc");
image();

Wh1.1eU)
{
x=dx/2.;y=yml=1.;ysold=1;
E. Program Listings 273

.., .. "........ , ............,,,,,,


.s:
" I. _-to "" . ..... .\
,
1-
yp1=step(&x,dx,&y,&ym1);
ysnew=(1.-yp1)*120;
if (abs (ysnew) >10000) break;
line(xs-1,ysold,xs,ysnew);
ysold=ysnew;
}
switch (getchO)
.r,
...... ,. ,... .,
-- .- 1\ l-t \
"'
... a.i:>'C
~.

.....1'.10 .loLl" \ . .". . ,


_... "" .......... v " .. ,

'C , U'C , U,A,J ,


,

default: getch();break;
case '+J : e=e+de;print(e,de,dx);break;
case J_ J . e=e-de;print(e,de,dx);break;
case 's J : de=destart;dx=dxstart;e=O.Ol*(int) (100*e);
print(e,de,dx);
break;
case J1 J : de=de/10.;print(e,de,dx);break;
1..1. _ ' ....l.. .. 1
,
'r . . . . .
............. J..:I J . . :1 ....=..:1.... /" ........; ... + ( ..... . :I.. . . :I....'.' ..
.
.J ,
," _'L ' , J
"

}/* main */

double step (double *xa, double dx. double *ya, double *ym1a)
i.
long i.n;
double k(double);
double yp1,x,y,ym1,xp1,xm1;

- . u=*u.... ~"",1""*~",,,1 ....


,'~~-tI\J 1~:'./r:.I\I\J\.
- " .. ". _A, """., ,
'.

for(i=l;i<=n;i++)
{
xp1=x+dx;
xm1=x-dx;
yp1=(2.*(1.-6./12.*dx*dx*k(x*y
-(1.+dx*dx/12.*k(xm1*ym1)/
(1 .l'Iv*l'Iv/1? *1r(v....1".
__ '1-_. ____ '1. - ... .
_._- -,- r-
.-t_ _.-t
1.... -1' 1 -1t' .. ,
}
*xa=x;
*ya=y;
*ymla-yml;
return yp1;
}

void
.[
. (I'In"hl ... A I'In"hl ... dA I'In"hl ... dy)

- ,- .. - ... ,
_\,~ _ _ +_r'll\nl

clearviewport();
274 E. Program Listings

setcolor(WHITE);
sprintf(str," E= X12.8lf , de=X12.8lf , dx= X12.8lf ". e .de.dx);
outtextxy(10.290,str);
re urn;

void image()

double k(double x)

Print II n Solitons nil


soliton = -2 Sech[x-4t]A2
plotl:= Plot3D[soliton,{x,-5.5}.{t,-1,1},PlotPoints->50]

{j.max}];
ListPlot[xulist,PlotJoined->True,PlotRange->All,
Frame -> True, Axes -> {True,False},
E. Program Listings 275
.
... ...... : - :
, .... ~,.
~ ....t'~
.. :""~"
... , 1.:1.
......._"
\-1'- --1''' -~.. -':'JI\~U.A. ~JJ '- .-"" "J
step2[u_.v_]:= (upl=RotateLeft[u]; up2=RotateLeft[upl];
uml=RotateRight[u]; um2=RotateRight[uml];
v+dt(2(uml+u+upl)*(upl-uml)/dx -
(up2-2upl+2uml-um2)/dx3 ) )
init:=(dx = 0.18; dt = .002; upast=uPast=ustart; time = dt;
dt=dt/l0; upres = firststep[upast];
Do[ufut=step2[upres.upast];upast=upres;upres=ufut.{9}];
= ..... ...1+ = +-i ....... ,
_.._-...,. ,.
.. -... ,,-- .... -.. ... --
.r..:ll--... ......
'C
_, .... 02r.: .1n' ._/T~r ..' .... r ..' " I nnl\ .: ~
c "--' -r~ r. ' ,...,...,...
"'I
'
~.
1..:11...
~.
,_
----,
"
~ ... L"~W'C--, UUI. ...... .u-... ........... .u-~.J ,

Do[ ufut=step2[upres.upast];
upast=upres;upres=ufut;time=time+dt.{fin}];
Print [IITime ".time];
xulist = Table [{ (j-max/2) *dx, ufut [Lj+l]]}.
{j.O.max}];
ts = StringJoinP'u(x.". ToString[time] II) II] ;
UU = Interpolation[xulist];
- _-_. ._in . n . ... .
.
D1,...+r....' rvl rv 1 1. D1 .n _~A11

_- _-- .. _..-
-~ .~. ~ -

...
~ _,

. ...
... .............
..._. _ A ..... _ _ , .., ._

.,.,
... -
"'V"~"I"''G ,
r,... ,...,...".,
LV. VUI..1

FrameLabel ->{"X". tS}] )

u2[x_.t_]=-12(3+4Cosh[2x-8t]+Cosh[4x-64t])/
(3Coshlx-28tJ+Coshl3x-36tJ)-2
plot4:=Plot3D[u2[x.t].{t.-.2 . 2}.{x,-5.5}.PlotPoints->50.
PlotRange -> {-10.0}.
.. . -
Shading -> False.
A -'> Th; rol
- - "': _ 7'"'" " _~
.1\
r,- ',. - _. ',. r_1 .. .. . 11.1.

--.,
~ ~ ~

n.' ..... f.. .. 1


_ _ 'W . . . __ ....
... , ... 1\
, _ ...oJ, ~"-

AxesLabel -> {IIt". "X". "U"}]

plot5:=ContourPlot[-u2[x.t].{t.-l.l}.{x.-10.10}.
PlotPoints->100.
ContourShading->False.
PlotRange -> All.
ContourSmoothing -> 4.
-

....
9 .. h ...l
........_,
_'> J'"+" " v ll'\.
_ ..... 1:".. ' - -
. .
... rn .. n n ~ LO"
1"1
...... ~, .... 1"
v.~~
.. ....
... .... n- ......A .......
I' I'
"'oJ ..

plot6[tt_:0.3]:= (uprime[x_]=D[u2[x.tt].x]; x=-10.0;


exactlist={{x.u2[x.tt]}}; d=0.07; upl=uprime[x]-2;
Wh11eLx<10 . upr=upr1meLx+dJ '2;
d = 0.07/Sqrt[1+Max[upl.upr]];
x = x+d; AppendTo[exactlist.{x.u2[x.tt]}];
upl=upr ];
T; o:+Plo't rl :lis't PI .... -> All
Pl
-
- :..... ..........
, A -'> - ::: " "7A ro OO?l
Av ...... _ ..... v,..._ ... 1 ,
, .~
276 E. Program Listings

A ~ T.'I'YIlo_...l
&'
...l co ,'I_ --11-
-<;;>
~
. i
. 10

Available on CD-ROM only.

D.~ nanaom l~umDers: ranaom.m


Print ["\n Random Numbers \n ll ]
xO = 1234
a = 106
c = 1283
m = ~n7f\
rndm[x_] = Mod[a*x + c,m]
uniform = NestList[rndm,xO,m+1]/N[mJ
triplet = Table[Take[uniform,{n,n+2}],{n,1,m,3}]
.
UIl~"v'C ... "v.l.~ -
.., '- ........
napL\tt/O)q.l.'l;Ltt.ttJJf, . il;J
. .
Pl.o't 1: =;:mow Lurapn1CS~lJ Lu'o1n'ti)1Ze LV. VVIiJ ,
Map[Point,unitvectors]}],
ViewPoint -) {2,3,2}]

vO = .f276. 164. 442.l/m (* vector closest to .f0 0 Ol *)


(* hi h? h~ Rn~n. llnH~ rAll *)
b1 = {-113. , 172., 7.}/m
b2 = {173., 113., -172.}/m
b3 = {345., 120., 570.}/m
,. ... , ...
vp - W"'\:1"'DJ. ___ , l.V,v,J.vvr
Pl.o't:l := i)nowLurapn1CS;JlJL1.1"01n'ti)1ZeLv.vV4J,
Map[Point,triplet]}],
ViewPoint -) vp]

uni = Table rRandomrl ..fm+211 .


t::ri = T~hlArT~lcArllni .(nn+2l1 .(nmll
univec = Map[(#/Sqrt[#.#])&,tri]
plot3:=Show[Graphics3D[{PointSize[0.004],
Map[Point,univec]}],
... . ,- _....
, .......................- ....
l.~,~,~rJ

5.1 Random Numbers: mzran.c

1***** Random Numbers *****1


#define N 1000000

unsigned long x=521288629, y=362436069, z=16163801,


,.=1 n=11':l11 .
unsigned long mzran()
{ unsigned long Sj

1t~y)X+C) ts=y ~x+C)j c=Uj)"


else {s=y-(x+c)-18j c=1j}
x=yj y=Zj Z=Sj n=69069*n+1013904243j
return (z+n);
E. Program Listings 277

maine)
{
double r=O.;
.long l.;
printf("\n\n 1,000,000 random numbers are generated II ,
II and averaged.\n\n");

for (i=O;i<N; i++)


r+=mzran()/4294967296.
~ (II r = 'llf \n" rl(~n.. 'hl.,.Hn
. -"-n
} g
.

_. --
~ ., 'r.'. ..... 1 A
--00- '"' _.._--
. ,:11 ... '"

/***** Fractal Aggregates *****/


#include <graphics.h>
#l.nclude <stdll.b.h>
#include <math.h>

#define lmax 220


#define rs (rmax+3.)
...... --'"
....~ r ro \

..... --'. _1.":"


,-- .
(1 nn .\

char xf[lmax] [lmax] ;


int rX,ry,maxx,maxy, count=O, color=O;
<1oUb.le rmax=l. ,pl.;

void main 0
{
void occupy(),jump(),aggregate(),circlejump();
,..h..... ."'- .. "\.
..... + ..:1_": - , _ .... ..:1 ......,
int i ,j;

initgraph (Il;driver, bode, "\\tc");


maxx=getmaxx~);

maxy=getmaxy();
setcolor(LIGHTGREEN);
settextstyle(1,O,1);
outtextxy(5,maxy-40,1I Diffusion Limited Aggregation");
.1,.,.... tWHI -..:
,l.,.rn n 1\
-" ..
outtextxy(maxx/2+30,maxy-30,"Commands: exit, arbitrary");
randomize 0 ;
pi=acos (-1.) ;

zor u.=u; l.<lomax; l.++)


for(j=O;J<lmax;J++) xf Ll.J LjJ =0;
xf[lmax/2] [lmax/2] =1;
278 E. Program Listings

J r " ,
.";~ "" .
while(1)
{
switch (checkO )
{
case 'k':occupy();jump();break;
case 'a':aggregate();occupy();jump()jbreak;
,. .. co ... ';'.;n_n(\.~........ 1r.

---- - ,~, ~..: ..:-:, _ ..: __ f \ . ' . .,


, J-r" ,
.J

if (kbhitO)
switch(getchO)
{
case J e J : closegraph();exit(1);
default : getchO ; break;
}
}/* while */
~ .
~/. _ .. oi ... 1

....
yu ....... "
J ......l ' \ 1
{
switch(random(4
{
case 0: rx+=1;break;
case 1: rx+=-1jbreak;
case 2: ry+=1;breakj
case 3: ry+=-1jbreak;
~
~

'\.
J

void aggregate 0
{
double x,y;
xf lrx+lmax/2J lry+lmax/2J =1;
x=rx;y=ry;
rmax= max(rmax.sqrt(x*x+y*y;
if(rmax>lmax/2.-5.) {printf(I\7") ;getchO ;exit(1);}
oi.f:(
_..: .,
'/1nn==n,
fA
.1,..... (,.,..1,....... fl,
II') ..
,1,..... (, .1'\
.f_. __ _':11'\\ II') I')~'~
.
, , . _ - '---'" - _J '--J --" -,-"
J

void occupy()
{
double phij
phi=(double)rand()/RAND_MAI*2.*pij
rx=rs*sin(phi)j
ry=rs*cos(phi);
1

void circlejump()
E. Program Listings 279

r
~

.oJ .L' 'L


... , .... ,J '1'.......
phi=(double)rand()/RAND_MAX.2 .pi;
x=rx; y=ry; r=sqrt(x.x+y.y);
rx+=(r-rs).sin(phi);
ry+~~r rs).cos~ph1);
}

char checkO
.f
rlnllhl ....... Y.V
... ,.......... ' .

y=ry;
r=sqrt(x.x+y.y);
if (r>rkill) return 'k' ;
1:r\.r.>:-ra) re'turn c' ;
if{xflrx+l+lmax/2JLry+lmax/2J
+xf[rx-1+lmax/2] [ry+lmax/2]
+xf[rx+lmax/2] [ry+l+lmax/2]
+yfrry+lm3y/?1 rrv1+1m3y/?1>O) , 3' .
... 1",... ,; , .
J '
"

.
l.

5.3 Percolation: perc.c and percgr.c

percgr . c is aVaiIaOle on
~

\jU- tU
~

J IVI amy.
.
I..... Percolation 1
'include <graphics.h>
'include <conio.h>
'include <stdlib.h>
'include <math.h>
..... ;ft(,

.
.r
int gdriver=DETECT,gmode;
double p=.59275;
int i,j,pr,L=700;

pr=p.RAND_MAX;
initgraph(&gdriver,&gmode,"\\tc");
for(i=O;i<L;i++)
for(j=O; j<L; j++)
;~( ...... ftrl{'<'n.... ' n"t-n;va1 (; ; WHIT":

.
&' &' &' 'J

g "," " J

closegraph 0 ;
}

.. T"lIo ..
tJ. ":I: C UJ.y J..I.J.CJ.
,... .. . J. &
. .\;

Available on CD-ROM only.


280 E. Program Listings
..... . . ,.
Fi.Fi T
.... -...

.... ....
1***** Ising Ferromagnet: Text Mode *****1
#include <time.h>
~t;1'Irln~A <C!+~l;'h 11'>
*.......1 ..:1_ 1.'-

#include <dos.h>
#define L 20
#define VSEG Oxb800

1nt s lL+2j lL+2j , bt l~j ;


double temp;

main 0
.(
...n;.:1 C!A+T(.:Inn'hlA)
void event(void);
void frame(int , int);
char ch;
1nt mcs,x,y,e,v;
clock_t start,end;
clrscrO;
randomize 0 ;
mcs=O;
- .----- (1'0 1)
~~ ( l i T ....... ""
: ........
r ~
.f:.
~ "' .
gotoxy(50,2);
printf("Monte Carlo simulation");
gotoxy(50,3);
pr1ntI l '::system S1ze 7.d * 7.d' ,L,L);
gotoxy 0, 25) ;
printf(" Commands: l(over),h(igher),j(ump),e(xit),arbitrary");
frame(2*L+3,L+2);

fnT(y=O~y<I+2~y++) fnT(v=O~v<1+2~v++) srylrvl=1


-fn.... (v=1v<L+1v++) -fn.... (...=1 ...<T.+1."...++)
-" ."
{
gotoxy(2*(x-l)+3,y+l);
putch(t) ;
1
getchU;
setT(2.269);
start=clock 0 ;
vhile(t)
.(
;-f ('W'h],;+n) n

for(x=l;x<L+l;x++) for(y=l;y<L+l;y++)
{
~ ~ p ~ p ,~p ~

e-s LXJ LyJ ... \ 5 LX-.LJ LyJ ~5 LX~.LJ LyJ ~5 LXJ


p ,~p ~ p ~ ~ ,

Ly-.LJ
~
~5
p ~ p ,~
LXJ Ly . .LJ ) ,
.
1Il e<u II randlj<DILe/:lJ )
i.
s [x] [y] =-s [x] [y] ;
E. Program Listings 281
~nn n .~\-'-"'\.
.-- .. , "'";::';~,~
_", ... 1, I,
"~ ... : ""
'-U-,OLAJ L;YJT.LI '.LiJ,

poke{VSEG,v,OxfOOlch)j
/* gotoxy{2*{x-1)+3,y+1)j */
/* putch{ch)j */
} /* if */
} /* for */
for{x=ljx<L+1jx++)
{
a rn1
- - -r.".1'- =a rr
_. 1 r.".1
_._-
- ..- -.. ...... - .. -....-. ,
~-

~rT .~,r_,_~r~,r_,.

r."rn' r~_,r,.,
g LAJ LVJ -g LAJ L ...J ,

s [X] [L+1] =s [X] [1] j


}
mcs++jgotoxy(50,15)jprintf(" mcs/spin %d",mcs)j ..
end=clock()j
gotoxy{50,16)j
printf{1I CPU time : y'.3e",(end-start)/CLK_TCK/{L*L)/mcs)j
} /* while */
,\1 ...... ; ... 1
~

.. -, . ~ , ...
"" "
vu.a.u. ;:>.,. ... 4
{
temp=tj
bf[2]=RAND_MAX*exp(-8./temp)j
bf[1]=RAND_MAX*exp(-4./temp)j
bf[O]=RAND_MAX/2j
gotoxy(50,10)jprintf{" Temperature: Y..2f",temp)j
}

;.:!
u ....

r ""
" switch(getchO)
{
case 'h':setT(temp+=.05)jbreakj
case '1':setT(temp-=.05)jbreakj
case ' j , : setT (1. ) jbreakj
default :getchO jbreakj
case 'e':clrscr()jexit(l)j
1-
'\
~

void frame(int xmax, int ymax)


{
int i=Oj

gotoxy(1, 1) j
while (i++, i<xmax) putch(205);
for{i=lji<ymax-1ji++)
.(
'1 ; +1)
: ..... ~~(10~' ,.
,---,
.
gotoxy(xmax,i+1)j
282 E. Program Listings
, . ft""

. ~
, ., J

.T
i=O;
gotoxy(l,ymax);
while(i++,i<xmax) putch(205);
gotoxy(l,l);putch(201);
gotoxy(xmax,l);putch(187);
gotoxy(l,ymax);putch(200);
gotoxy(xmax,ymax);putch(188);
~
I

5.6 Traveling Salesman Problem: travel.c

Available on CD-ROM only.


Index

... .,
& ....
. n
OJ
T'" . LJ .' , ......,,,,,, ,.1 ... '~r!:
I I , .LV"", .L-S I , .LVU

AccuracyGoal 86 - periodic 60,73,195


Aggregate 166,167 break 112,229
- fractal 170 Bulirsch-Stoer method 119
Aliasin~ 17
Alternating current 52 case 112
Alternating voltage 52 CDF 26
Amplitude equation 140,143 ceil 133
I::.Il .... .1 1~~~. ,~ 1111

A
A

" "
~~

.10 ... , ...", rl1..


. .~ & U ~~~

0' 0", 0"7


-su, ... , u ... ,uu,u
& ~ .......
,&.
U
., n1 nn

Apply 4
-J ..1
char 5,225
o~,ou

Approximation 48, 138 Charge distribution 30


ArcSin 8,213 Charge, total 31
Array, two-dimensional 168 Chirikov map 94
Arrhenius' law 198,202 X'" distribution 24,26
AspectRatio 105,213 ChiSquareDistribution 26
Assignment 54 X2 test 23
.. +n; ?n~ r.hnn R? ?lR
A
~ ,
0'7 11lA
,,,,,, ~~ , 1')<)
~
('0,,; ...:,, __

.,
'11
r;:
~
" ... ~u
.1.
-~ u

- strange 123 Cluster 165,171,172,175,177,180


Automatic 105,213 Coexistence 40
Average 138 Compilation 6
- statistical l~a,l~~ Lioncentratlon, CritICal n:t:
- thermal 199 Confidence interval 24, 26
- weighted 20 Confidence level 29
Contour 27,32
Band 65 78 r.j 'Pln+ Q ~? ?14
- chaotic 90127 ('O,._ .. ~._- a
,
T'"
~ Ell' r"1. ")'1
"'-
Basin of attraction 123 Control parameter 129,199
Benard experiment 129 Convection cell 127
Bessel function 21 Convergence 109
~ ~ ~
DeSSe.LJ ,~a, ~~.:>, ~~o LionvolutlOn 14,~1
.tnIurcatlon POInt lS4 Coordinate representation 47,145
Bloch theorem 65 Correlation 159
Block 4,86,218
Boltzmann constant 39 190
- length 175,193,197
n .. . 140
Boltzmann factor 196 202 204 ~.
~~
4R 71 7~
Ronfl 176
&
284 Index
rI. , .
- ..."''''Vl' ., ...
.
rI .. 1

...... -.-
LJ~~
, ,
--
UVU, - - ~~AV,J
,
~~

Critical exponent see Exponent, Dynamic


critical - continuous 94
Critical phenomenon 172 - symbolic 84,90,92
Critical slowin~ down 199
Crystal, aperiodic 19 Eigenmode 61,63,139
Curl 37 Eigenstate 47,65,77,131,145
Current density 146, 166 Eigensystem 76,221
r'l.....1""
~,J .~
--, 1')7
QQ T'""
...., - '.
~- -.
A'7_ .AfI r::fI ~1
-~, ~~, --, ~r::
-~,~.,
~'7 ~fI
~~,

-u .....
oJ
- ...............
I, ~u, "'~~
'7C

~"A
'70 1<)1
v, .v, ....,... , .....,
~
1..11::

,-I, iJ.l,
...
U.l
~

Data - - generalized 60
- nOISY 22 - problem 66
- smoothed 21 Eigenvalues 49,62,76,221
default 112,229 Ei~envector 47,59,61,66,76
#define 5,125,227 Elliptic integral 7
Degeneracy 78 EllipticE 35
Derivative ,39,84 EllipticF 8
..
. .,. --...
lA'l 1:'"..:_... ..:_u o 1'1 'l~
...
...........
A' - - - . . ...." -_, ... ~

. .-
101"7 nno
...... '''- -. ,.
"1"7
.. ,.., ............. ,..
~OiJ,~~~,~~~
T'"'
.cJllU- lIV-t:llU
...u., """"u
..,..,.....................
~O"',~OoJ,~ou
~

Determinant 72 Energy 190,202


Deterministic system 113 - eigenvalue 50,131
Deviation, quadratic 24 - landscape 208
Devil's staircase 99 - level 42,51,77,134
DiagonalMatrix 49,61,220 Equation
Difference equation 137,149 - implicit 149
Differential equation 82,203 - of motion 60, 118, 120
,.
_ ..... 1.-
,.
.~-
,
117 ~o
11 ~
_-v
11'"
....& n.~
~.
I'n .."'..

An
~v~v~
... ,
~o

.......,
'lO

V" v
...... U
.""
- partial 136,144,148 Equations, system of 52,56
Diffusion 164,195,198 - linear 47,59
- equation 164 Equilibrium, thermal 190-192, 195,
- - radially symmetric 166 198,202,203
- limited aggregation 164 Error, local 118
Dimension Euler method 116, 119, 120
- embedding 102 Euler step 118,148
.. .1 1(\') 1')'1
, ---, l~A
--, 1'71 , 17A , 1'7~ 1:'..... 1 ..... + ... g
-
10'1
....... .Lv"',.Lv",
10n
-~

. .......
~,

-....... .. '7~ '11A


.v, ... .L.., .........
'1'1'l


-... orr
.,.., .. - rr - 1 ....
.L'2:U

Dipole moment 30,32 Expansion, symbolic 11


Distribution Explosion criterion 134
- initial 146 Exponent, critical 174, 181, 182, 193,
- - symmetrized 148 199
- stationary 185 Expression, logical 54
Do 4,86,138,141,219
Domain wall 195,198 Fast Fourier Transform (FFT) 15
~'l ~~
nn+ 'l1
, ')')1 ......
-4l __~
.1..

.1..,
~

r-.
~
_1...1
~ '1'1l:::
v, __ '"

.. v
1"70
U
----
.. ---
"".
11 '1
11 n
.L.L""
Double-well potential 51,121,135 Fibonacci number 19
Index 285

- .
.... ;"'1~ ')0 ("1

. .". 1 nO 11 n
,. ...
- .., ,., _.-
.~.~ ~~
"
... ..,'"', ...... v
'In rt
vv VI

- magnetic 34,63 Golden ratio 98


Filter 56 Gradient 30,36
FindMinimum 25 Graphics 31,105
FindRoot 41,84-86,98,218,221 Graphics object 31, 105, 158
Finite size scaling 175, 178, 181, 193, Graphics3D 159
199 Grassberger, P. 123
First 95 Ground state 76,78,94,99,131
Ji'lr ?"l. ?h hO 70 '>Wl
.
"P

'[;I,'
~ ~J ~.~
.1 00 no')
~~,~-
.....
~_~
. .
u __
~
,
-
1 "70 1 Oil
...,,_~v

D.' .J ' on 0,., rt. I 1 ~ A 1 ......


... &A,",U PV&&&U u~,u. " " ........ u __ ..- ... V"Z, . . . . .

Flatten 62,74,105
float 5,225 Hamiltonian 48,51,71,73,75,119,
Flory, P.J. 182 149
fl'luctuatlOn 175,192,195,198,199 - normalized 145
Flux Harper equation 64,66,70
- area-preservmg 94 Hermite polynomial 48
- magnetic 64 Histogram 86
Ji'111'V J.Ti+ ..
~
'r--
.. 110')
-~-
RLl
IT" L.,.&

TT'-:'
;. , _.n 110 11'>
&:.').,
~~

~'l ,.,n
.........
... A
-.:,~
n1 n
... ., I 1 n
oJ
VV v

for 5,33,179,196,226,229 Hoshen, J. 177


Force Hubbard, J. 71
- gravitational 120 Hyperplane 108,109
- perIodic l~~
Forward-two-point formula 137 If 41,76,218,219
Four-cycle 83,90 Impedance, complex 52
Fourier 8, 15 Implicit method 144
"LI:!
T'\
fifi fH ... ,..1 111'1 ... fi l?fi ??7
T'\ T .. " l'
(;101'10(;1 R hLl 1 '>.11

- 52,55,60,152,210
T.'I ~
, -v, _.. . _.. ,
"7 11l 1') 1')1 T ..

"-oJ
-_ .
11')..4

Initial condition 61,83,121,165


- inverse 13,55 Initial state see state, initial
Fractal 102,105,123,173 Initial value 116,132
ttrequency Imtlal-value problem 104
- angular 52 Initialization 138
- fundamental 146 int 5,225
- incommensurate 97 Integrate 9,11,37,220
R~
T 1
14R
""- ," . 1 '>0 T
U
1
1'>1:;.
..., r
T.'I 1nn T 1 ')')
... .,., ou,",t' ... vv
-...,

Function
u
I .... ,
nteractlOn
- Boolean 108 - attractive 183
- nonlinear 93 - magnetic 172
InteractIOn potential !J;j
Gam 42,44 Interference pattern 146,153
Game of chance 46 Interpolation 141
Game theory 42 Inverse 61,221
~ . 24 ~ ~
'lIer 15" 21
~~j;l ~Q 1?~
T 1
.1
n. .. .. ,
'>0 1~'l T
". u",l11 0 ~I:;.
gcc 6,240 Ising ferromagnet 192,197
286 Index

Isotropy 165
Iteration 84
- inverse 85,90,150

KAM orbit 98 100


Kernel 20
Keyboard buffer 206 Minimax theorem 44
Kirchhoff's law 52 Minimum, absolute 202
Koch curve 106 Mod 96,158
o e unc ion
o u e
Modulo function 95, 158, 161, 187, 227
Lattice Molecular dynamics 118
- cubic 164 Momentum 0 erator 64
- gas Monomer 102
- square 172
- triangular 172 204
- vector, primitive 159 Monte Carlo step 210
- vibration 59, 62 Multiparticle state 71, 74, 190

- rule 107
Leath, P.L. 177
Length 4,76,216
Line
Line integral 36
LinearProgramming 42,45 Network
Liouville's theorem 94 - electrical 52
Liquid 39 - linear 54

Nonlinearity 7
83,91 NonlinearRegress 25,217
Normal mode 60

,
132

185,191
Index 287

- algebra 74 190, 198


- unitary 149 Phase velocity 152
Optimization Phonon 59,62
- com inatorial 203 Pixel 86,103,134
- continuous 201 Plot 8, 141, 213
- discrete 201 Plot3D 32,213
- linear 42,44,201 PlotRange 8

, ,
- superstable 84,85,90 Poincare section 82,94, 123, 126
Order Point 159
- magnetic 172 Pointer 5, 230, 233
r er parameter Polygon 10
Oscillation 138 Polymer configuration 183
- damped 126 Polymer dynamics 183
- longitudinal 59 Polymer molecule 102,182,186

Oscillatory circuit 52

54,58

27
23,28
37,214

42,43,46 Power spectrum 19


Precision 91
19,210 Predictor-corrector method 119

, printf ,
9 Probability 43, 145
122 - density 164

172,175

74,216
49,83

Phase space 9, 11, 120, 122 Quantum Monte Carlo method 78


288 Index

y , ,
rand 5,103,158,168,177,206,230 - time-dependent 144
RAND~AX 5,168,170,230 Schroeder, M. 106
Random 4,158,159,214 Sech 138
random 96 Self-avoidin walk SAW 182
Random motion 164 Self-intersection 184
Random number 4,21,46,113,157, Self-similarity 104
205 Sequence, periodic 158

- - subtract-with-borrow 160 Series representation 145


- normally distributed 29 Shooting method 132,135
- uniformly distributed 162, 195 Show 31,213,216
Random vector 102 ShowPro ress 26
Random walk 102, 103, 164, 182, 183, Sierpinski gasket 104
189 Sign change 67,68
Rectangular voltage 58 Simplify 38,220

Relaxation time 195 Single-particle state 71


Renormalization group theory 174, Site percolation 176
193 Size, average 165, 173
Re lacePart 75 Soliton 136
Reptation 184-186 Solution
Resonance 54,56,57 - analytic 41
- curve 56 - numerical 41,47,51, 71,115, 141

,
Richardson extrapolation 118 Spectrum 63
Rosenblatt, F. 109 Spin configuration 191
Rosenblatt rule 110 Spin correlation 80
RotateLeft 21,138,141 Spin lass 202
RotateRight 141 Sqrt 9,49,212
Round 119 Stability 143
Round trip 200 - condition 143

State 94
163 - commensurate 95,97
- incommensurate 98, 99
- initial 83, 150
- quasiperiodic 98
- stable 93
- stationary 47, 145, 191
Index 289

,
- stochastic 44 Two-cycle 83
Stroboscopic illumination 123 Two-person zero-sum game 43, 46
struct 103,178,186,205 Two-phase line 39,40
Sturm se uence 67 Two- hase mixture 40
Subharmonic 83 Two-soliton solution 142
Sum 32,75 Type declaration 5, 103, 225
Supercomputer 191 typedef 161,186,205

, , ,
switch 112,169,228 unsigned long int 161
Symmetry 66,68,69,74,78,131,133,
145,146,193 Vacuum 72
- reaking, spontaneous 19 van er s equatIon
Synapse 106 van der Waals gas 38
Synaptic plasticity 108 Variance 24,162,200
Synaptic strength 108 Vector 4,30,229

Taylor expansion 116, 132, 139, 153


Temperature
- critical 39, 41
- norm lze
Tensor 4,30
TeXForm 12,77
Thickness 31

Time derivative 140 - Gaussian


Time evolution 149, 153
- operator 148 155
- quantum-mec amc
Time scale 123,198
- characteristic 152 183
Time series 110 107,112

,
Transition probability 185, 191, 194, Winding number 95,97,99
196,202 - rational 97
Translation 60 Witten, T.A. 163
- opera or or 1ng reC1S10n
- t eorem
Traveling salesman 200 Zaman, A. 160
L

~'Gdby~
CN' ~
~
CP ;:,-
~

.)0~

L
~nrinn~r
-'" t"'. ~ ~

and the
environment
At ~pnnger we nrmly Delleve tnat an
international science publisher has a
special obligation to the environment,
and our cornorate nolicies consistently.
~ ~

reflect this conviction.


We also expect our business partners -
""",;11 ... . _1. .
.1" -.1" U&&&&U, .1" .u, .1" OJ OJ

manufacturers, etc. - to commit


themselves to using materials and
r-
, . ,
.1"
, "
Ulal uu llU l

the environment. The paper in this


book is made from low- or no-chlorine
pulp and IS aCId tree, In contormance
. .
WIUI
" . ,
IIII~J I'"
, , r
I, Jill .... ~I
.U" IUI.1" T

permanency.

~
-~

~4~
~
Springer
w. Kinzel/G. Reents

Ph~sics
bq
C0m PUte r
Computational Physics has under-
gone rapid development in recent
years and is being integrated into
physics education as a standard part. This course,
intended for upper-division undergraduate or grad-
uate students, was designed by W. Kinzel and
G. Reents as a textbook in computational physics
but may also serve as a supplement to courses in
theoretical physics.
It is an introduction to the solution of physical models
by computer. The programs developed in this book
are based on the modern computer languages
Mathematica and C and are written for PCs as well
as for workstations. 28 examples from different fields
of physics are worked out, including chaos, fractals,
the Hofstadter butterfly, phase transitions, Monte-
Carlo simulations, percolation, polymers, combinato-
rial optimization, neural networks, and game theory.
Detailed explanation of the algorithms and computer
programs together with source files and graphics
routines help the student gain thorough experience
right from the start.
System requirements: Mathematica 2.2 or 3.0,
C compiler.

ISBN 3-540-62743-X

I I II
9 783540 627432

http://www.springer.de

You might also like