Sie sind auf Seite 1von 299

w. Kinzel/G.

Reents

Ie

b~

ut

Programming Physical Problems


Using Mathematica and C

Springer

W
..

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


.....

r-.

r-."

Dr. Martin Clajus


r-.....

....

ve; ve;lj'

.~..

-....,.vi.]US

~,

r l tV.-UU:.G. UI. Ut:UI ~ ...

Uf.

Institut fUr Theoretische physik


UniversiUit Wiirzburg
Am Hubland
D-97074 Wiirzburg
e-maIl:
kinzel@physik.um-wuerzburg.de
reents@physik.uni-wuerzburg.de

Deot. of Physics & Astronomv


UCLA
Box 951547

Los Angeles, CA 90095-1547, USA


e-maIl:
c1a}us@physics.ucla.edu

The cover picture shows a space-time diagram of the probability of presence of a quantum 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'"

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-"

,en;. In mls.

HV'"

,....

. uoes nor implY' even


. in
.............

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, Germany, for physics majors after their fourth semester - those having completed
the introductor c r w
i

VI

Preface

..

"

"

1""".1 OJ.'-'O

...

~ ~
,

oVJ.J.J.'-' v...

." ..1.

~ ,~ ~~ ~I. ~

'H J.J.J.'-'J.J. ....... '-' .... u

..1

UJ.J.'-'

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. Although a CD-ROM with finished programs is enclosed with the book, they are
.
.
not meant as user-rnenOlY experimental environments. --~
we .nope tnat insteaa
they can be taken as a starting-point, and we encourage our readers to modify 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
A

UTO UTlc:!h tn

'

n11l" th~n1rc:! Wo

..

11

ll1ro
"C

.,

tn

1\11" Rlohl

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........
T
n n
Con"",..; ..1 th:lnk~ uo to t.hp.
11
.
.... "..,. .. . ..
....
. .1.1.
V,
1\ If.
.1.
.
.... ~"'9'
....
""'.~
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

~~

..

'C

..

.
""

.1.1.
....

IIJ.J... O

I.

.:L

'C

v ..
TTT.

10""

., ..

J.J.""V

T':'

J.'.La... IIJ.J.J.

r. . . .

.
...

UJ.J.~

...... .

....

TrT
'0

July, 1997

'

J~ .
'07

'V.:... _~l

.....

U 'UN,",U

'" 07

Georg Reents

Contents

1.

..

or

Functions In Mathematica

1 1
4

....

L~

..

..................................................

..,.

,.

.... T

.-n1

~lle

~-

1...

T"Io

'I
1

.I.

...............................
. ..............................
...............................

3
A

,.

1.3 Fourier Transformations ................................. 13


1.4 Smoothing of Data ..................................... 20
,.
...... .......................................... nn
4

2.

..

.... T

LtJ

.1'

1.6
1.7
1.8
1.9

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


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

~tJ

.I'lL

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


2.1 The Quantum Oscillator ............................... 47
2.2 Electrical Circuits ...................................... 52
?~

nh::lln vp

mI.
TT
.I. .l.l'V

AI

"'."'1:

r.

Tt

~~

~1

. ...................................
3.2 The Frenkel-Kontorova Model ........................... 93
3.3 Fractal Lattices ........................................ 101
.

.., .1.

~.
.I.

1\.T.

AI

"'."'1:

4.

............................... v..,
.................................... 71
.V
.,

2.5 The Hubbard Model


3

!iQ

,..

T"Io

'I

.1

.I

&

_I 1\.T

~~6~&

.1

T"

n ..

JJ)

O~

1
~v ~&&.~

Dilterentlal Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..
4.1 The Runge-Kutta Method ...............................
4.2 The Chaotic Pendulum ..................................
4.;1 ~tatlonary ~tates .......................................
4.4 Solitons ...............................................
4.5 Time-dependent Schrodinger Equation ....................

..

n~

..L.UV

115

115
121
IJU

136
144

VIII
I!'

u.

Contents
1\/L

.1

C".

_'I

.L.

1~'"
.LV,

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


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

,')Ji

5.5
5.6
A.

rOlymer vllaInS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101


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

..
. . --a.,;nemanca

-. .:neps wun
.rlrs't
~

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 comx

codes are available on the enclosed CD-ROM. In the results part, some results 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.

,IS 0 ten use or


-intensive computer simu ations.
over e ements 0
MAPLE is also a very popular tool for computer algebra. All of our programs run not only on fast workstations, but also on a PC operating under
or mux.

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


M athematica
1. Functions In

..

,.
.
- .
.................. u .lUC.l
.lCVC.l U.l p.l
.
......
......
...... , CL.l.l'y
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 mathematical 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
~4-9.1~ 99.:11
~ 14-:~1~
~-~~
u'" ................ A..., ................., .... 0"''''.....
.... "'......
...... "'UJ""'" ." .........................
..
.....
levels of modules; this has the advantage of simplifying the modification of
such programs by making it more likely that only individual functions will
...

nil

II.l.le

I'

o.

..

l. n

_L

J.,."
....""..."
...... 4-,..
u..............

.- .
lV1 a~nemanca
.

-l

.......
. .
IS a programmIng language

. lug
.

.large

UI
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

"
LUCLL
I:)

CL1:l CL

..

.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
,-' .'......

..
I

,~

......

......

......

rr

~ -~~

......

'~~1

......

and

......

..

'-

.1

1'

(after all, Mathematica is written in C), require much more effort than Mathematica in order to, say, generate a graph of a Bessel function in the complex
..nlane.
'T'1-.:~ ~1-.~~4-~

............,

....,

:~.

-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..
. .Za1JIUIl.
Ul
, aIla
...

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 callmg 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 Mathematica. 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; nevertheless, we want to point out some features of this language here: the underscore 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

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++
return sum/n;

sum=sum+data i

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

1. Functions in M athematica

Literature

Wolfram S. (1996) The Mathematica Book, 3rd ed. Wolfram Media, Champaign, 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

cos <P - cos <Po

1.3

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

<Po
which results in the following integral:

1.

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

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


function of CPo:

Jf79

= 1. The command Plot draws the period as a


-)

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 nonlinearity CPo, we expand cp(t) into a Fourier series. This is most easily acil _.
lish
in h

1.2 The Nonlineax Pendulum


."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

hv
.- r~l1infJ" r

lL

,.,

r .....

'"'v.u. ... vu..Li:> .... 1.J;o.L,

... ....

"', 01:

for t.hp

....

.J

1-

"".. "1

J;o~,

~J

~a.u

tJv

1-

UOVU

lIV

R(ln
,

.1

'IJ

ua.vv

1'hp

II))

.-'1

.
"'V.L

.L-

various values of E.
Finally, a remark concerning the series expansion of T(cpo). The new ver-

(q {\\

"'.LV.L.L

\ V.V

II

_11"_ ~,,_ _

lL

"'~.L

V.L

"P_ l__

l'

....

-..-

~'-J

_.f (1 7\ hn
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

.11 ;:>qrl;; L.1

:r -

.~

;:>~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

()

- = Series

rf

fT

{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

..

~,,-

.J.lIJ, VJ.J.

lIJ.J.V

'

of t.hp

rr

. ,,VI.

l'

.J

lIUv ..-

~1

.1

{I)n

T.'~

_1

...

...

i~::t.

of t.hp

.I: J.5Ul.V

.1-

.............. ~

.1....

1IJ.J.'-' ..-

.J fJ'1
.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

4Pi
2Pi

()

Pi/4

Pi/2

3Pil4

Pi

Tne penOd 1. as a tunction of the amplitude <po


~lg.

phiO

L 1.

10

1. Functions in Mathematica
I

0.5

Fig. 1.2. Normalized displacement lpnorm (t /T) of

-0.5

0.2

0.4

0.8

0.6
tff

71",71",
and 99971"/1000
inside out)

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

....,
.......

~4

......
'"

<

0
2

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

184041 Pi Sin[----]

P 1
41409225 Pi Sin[----]

> --------------------- + ----------------------- +


phiO 18
147744025 Pi Sin[----]

phiO 20
2133423721 Pi Sin[----]

-3
-Pi

-Pi/2

o
phi

Pil2

Pi

12

1. Functions in Mathematica

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

8192

128

32

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

!EQ.
2

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:
Iteration:
Sto :

bo = COSct,
bi+l = Vaibi ,
- 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 transunc 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)

ar

--

'" b
. (r - 1) (8 - 1)
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-

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 ~
= - - LJ a r exp

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

27fl

(1.12)

A useful property of Fourier transforms becomes evident in the convolution of two sequences {/r} and {gr}. In this operation, the elements Ir

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

. (m - 1) (j - 1)
N

Ir+l-j =

N_

Lin exp

. (n - 1) (r - j)
27fl....:.....---:.....-'------.;....;...
N

15

1.3 Fourier Transformations


I

'\

h. - I --.::..- \

'\' n.
L...J
"
\yN} r,j,m,n

.I.

. (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

Avn

L.J

-r

(?'7I"l
\

t:....:l

lq.) NJ

1\T Ji
.

.,,""
.

... ,

lo

'71.

t=.

and we are left with

hs = VN

L iJmin exp (2~i


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

m,n

(1.14)

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

l:!...
)

(".

fl.'l Is

2~i

exp

'

l'-, ,

(r:

lV

n
"

(1.15)

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
.
,
,
.1)
.1)
~
~
2 . ~1'
Ws,r (N) =
exp ~l
N

IN

~,

bv a vector a -

(a, .. aJ\T)

"''O.'''........... ~
'V

'V~,

'V..-&

.1 ,1.
&

this takes N2 stens. The FFT allrorithm how-

+l.", ............. '" ;~ .... ..,......... l."'... ,..~ "'+"'Y"'" +h .... +


U&&'V

.... ..-~&'V

&&~

....

""~

.... u ' V , t ' ....

U&&.... u

---

_ -

--

.1 __ ~~
.1 .....,

...,......

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

1. Functions in Mathematica

16

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)

bs

v'N -

(N - 2) (s - 1)]
exp 1 71"
N
[.

00

(1.22)

fI-s+kN.

k=-oo

00

(1.23)

fI-s+kN

k=-oo

' 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

1. Functions in Mathematica

18

0.2 .,

0.15

0.1

\
--

\ ~
--...VV~
.......
........_ _--'-----'

\/
0'--

..........

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

IV

.V

0.8

0.75

0.6

0.5
0.25

0.4

0.2

-0.25

-0.5

-~

AO _._. -

J~~

._--

..

..

- -

~J-'

-~

..

V"

.
0;"00'

inverse Fourier transformation to continuous t values

IAAA

.... AA

..

ro.f 4-l. .... "

-- ---

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.

V'"

s=-N/2+1

I.

'"

~r

1) ~S -

1)

\"rj

1
=
V

N/2

r:-;

lV

s-I

bs exp

. (r - 1) (s - 1)
21rI
1\1

.l.Y

1 ~
+ ..;N LJ

s'-N/2

[ 2 . (r - 1) (Sf - N /2 - 1)]
11"1
N

exp -

s'-1
I\T J?

..;N ~

.
Ds

exp

. ~1I"1

r-1)(s-l)
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.. }

2. Aperiodic crystal. Assume a chain of atoms with a periodic arrangement.

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:

(ii) Generate the next line by appending the next-to-Iast line to the
last one.

1. Functions in M athematica

20

Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Redwood 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

= 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

.(8 - 1) (r

1)

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, Champaign, 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 =
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:

u;.

(1.28)

(X~) = r

() /

N-M
1
e- t t-2-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 =
is again distributed
according to the distribution function P from (1.29), this time with M rather
X2 (a)

X2 (ao)

(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 surface onto the axis i then yields the error interval for the parameter ai.

m
For the nonlinear fit, too, it is easiest to use the functions available in Mathematica. 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 intermediate 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

dx

= 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
,

. .,

We obtain the confidence interval for the value of X~ from

1.5 Nonlinear Fit

Fig. 1.8. Damped oscillation and noisy data

10

chi2

27

15

20

Fig. 1.9. X density distribution with seven degrees of freedom

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

1. Functions in Mathematica

28
0.2

0.14

/)J
11/

0.15
~

V.I

//

..,;)

0.05

0.12

0.4

0.8

0.6

*l

0.06
0.04

............

v.v..:.

1 111

'CO

~J
..-/'

0
0.9 0.92 0.94 0.96 0.98

1.2

a
'INa

'\

OOR

f L..-//
l/

0.1

//

1.02 1.04

om
,,2(.n)

nf

""

space (left) and with the

om-b

UTifh fho ... _h .... 1"'.... 0 i ....

-~

plane (right)

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

'0'

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 narrow If onp nlot.~ f

....""
..... v ~ ...

.L~

..J"
a..uu

rt: 1

v~ll1p~ frmn F'i IT 1 10

for two

"" ........
""
..... 'v,

CLv.~,

D,'

v.uoc;

~a.u

ooc;oc; .L.U

.I.' .LE)

., .,.,
.1. .1..1.

.1..

Ll.
lIua.lI UVlIU

-'I

-'I'

~....

4-1.
u .. ~'"

4- 1.
u ...."'v.. J

.1.

u .. ~"'.. '"

~U.L

'11
voc;o OllU.l .loc;p-

= 11) and the


, ,.

1
~o

~
J

resent the data relatively well. The small number of data (N


large error do not permit a better fit.
.< ... 0

;:1..:1

,1.

..... 1..

J.VJ.

V'"

LW."

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

0.5
';:;'

.....

0.25
~

-0.25

/""'\.
\

A ,.

-0.5

Fig. 1.11. Two fit curves


, ~-

..........."

I'

6
t

J.,J.VJ.""

lIt:u,

UV.lll

lI.l.lt:

VUlIt:l'

~Vll-

liour OI line a-D plOli snown


in Fig. 1.10

1.5 Nonlinear Fit

29

Fig. 1.12. Parameter values a and


0.5 0.6 0.7 0.8 0.9

1.1

1.2

b from the fits of the artificial data

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) Numerical 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 -

4>(r) = r

+ - r 3 + -rQr+O
2r 5

r(i) ~ 00,

(1.34)

1.6 Multipole Expansion

ei,
i=l

where

ri

P=

31

ei r (i),

Q kl =

i=l

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

...

..

c:
~

0.5

Ss

a:"'.....'J7

>.

""

EIb

'V'J

-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


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

.1

,'I..

r.

,U.l

lJ.l.l{;;

.lV.l.l.l.l

.11

" ............ J'"

V.l

..

..1

(ld..lU

r
VUlJ

V.l

.'1..
lJ.l.l{;;

"'"

-Y

1
A

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,~"
_.. .
'L'"

... L L .... .J .J

q~wn

-~

T~

. r r .. "

.........

i LLL~JJ

,..,

r" __"

...... L ....'

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

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

-~

..

r,o

....

r ...... ,

........ .I.~ ........I.J


_....
r.
_ , ..

v.J.~

...

'LL'L~"OJJ ,"l~,OfJ

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 immediately. 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

r.

.lV.l

l.J.l{;;V.llJ'y,

.1

:l.
"

'T'hp

nof: r

r_
.r

V.l

..1"

,.

" .'1..

,0

vv .llJ.l~

a..l.l

a..l

...'I

hv

:l.

rlot (.,

oJ

'.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 generate 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....._ _---'-_ _--....~


-2
-1
0

._J

Fig. 1.15. The same potential as in


Fi. 1.14 but dis la ed as a contour lot

Fig. 1.16. The exact potential (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

- 1// /

\\ ~\ ~\ '\
" " ","
--\ ",,,,,, - -

I. 1

----//////Il
...
---//// / / / I l
-10 ----//////1111

Fig. 1.17. The direction


of the electric field of the
ten unit charges in the

\ \ \ \ '\ " " " " ' "

~\\\\'\'"''''''

11)

35

11)

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

uy

Lilt:

At/J (r 0)

or.....

or

= fLo

J.U.

1("

gl vt:~ Lilt:

[(2 - k

Ia
Ja 2

+ r + 2arsinO
2

2
)

K (k) - 2E (k)]
k2

,y .........

k2 =
a2

4ar sinO
.
2
+ r + 2arsinO

Rllinr,icKrk-21

K(k)

.....

'V..

and

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

Rllin'HrJ;'rk-21

E(k)

...........

are the

.1

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

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

nint

~applies

. .

- -

. .

--

.--

36

1. Functions in M athematica

Gradshteyn I.S., Ryzhik I.M. (1994) Table of Integrals, Series, and Products.
Academic Press, Boston, MA
., ac man
Addison-Wesley, Reading, MA
Wickham-Jones T. (1994) Mathematica Graphics: Techniques & Applicaml

1.7 Line Integrals

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

..

F=

...

t;

-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}.

38

1. Functions in M athematica
r

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

,
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 derees 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 -

(1.40)

b) = NkBT

,
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
c
T = 27NkBb' ~

= 3b,

Pc

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


,

a
27b2

(1.42)

(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

l. Functions in M athematica

40
Vft

- Jr p( V)d
V = Pt
VI
~lJ

Pt, _ga:s

VI

<

<

1-

. ..nqulU..

~IlU

VI) .

~ V3 -

are

(1.44)

. .

.ly

.. .

T-P

"
lur
au v

..

..

WllJn

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~

+_h~4o

.ii.
-

,~

. .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)
....... A
~

....

'

,..

....

- ;t/v-?

lo 'h.n lo.nn
~

(1 111\.

..

'/

eq1=D[p,v]==Q
eq2=D[p,{v,2}]==Q
,
, ,
,.

TT

nel-e,

au

LIlt: OJJ ...... ..,,,..

,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 , ....

..,

.... J

_ ....

-~I

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

..

""',,"
t'h",t
-J

eq3=p[v1]==p[v3]

,~

"'1

..

an" '" H t" nf


~

1.8 Maxwell Construction

'1"'1-. ~

.J

.&. ........

~~~

""........

41

..

.. 1-.~ .. ~.~ ~_~~~


.. ~ {1 AA\
v........ v
""................... ..............""............. 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

..

..

.. I. ~ l I r il.
V"''''', V" ....... " .L ............. v .........

...

'1"'1.

V~IV

and ~

thp.

.-t.

of thp.

., .,

r .....

.J '" . ,
r. r ..'
.... v~V .... L'p LV.I

i'

-.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.
tho
iho'l '1"1(17\ in tho CT~'l
'T'ho tnn
.,
.....
r, I
....
.....
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
O'

J.J.J.

.) ~mrl ~. .....

~"i'

... ,

A )onu t.hp .. ~.~

.1-

.....

linp

.1-

1"

..

'.J

~.nrl U~R

.....

--

1. IJ

1.5
1 ')l\

c..

\~-~
--

0.75

\/

f\,

~.~

~......-.-..

\/

0.25
0

1.

V
"":...

..

_e

.. 0

,.

--

..

l\Jf

,
-s.-

~~_ ..1-."

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

,;:,

oL

.L

~~

v .... ~

.L

....

~ ..:1,,_ "'X7........ 1...

~ ....

~ ~~

~~..

~~"

v.~tJ, v'~"',

-~

~~

~'1'

V.otJ \ "up loU

T... ~ ..-

~~_

..1-."

.. ~ ..

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]
ew or
Schmid E.W., Spitz G., Losch W. (1990) Theoretical Physics on the Personal Computer. Springer, Berlin, Heidelberg, New York
1,

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

, . .,

K=

1 3 1
-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
e I ea 0 c oose e co umn a Yle s e sma es oss m e
up WI
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
as closer ins ection of the a out table
ever reason to rethink his strate
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:
i,j

Pi qj K ij .

(1.46)

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
4 with i > 0 and 1 + 2 + 3 + 4 = 1 we have
choice
i,j

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

LP?Kij

> K o for all j

If we assume that
l:X?Kij

> 0 then with

> 1 for all j

(1.51)

. K 0 this becomes

(1.52)

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

Xl,X2,X3
strategy Po

WI

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

= {1,

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

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 functions !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 o + Aq

(2.3)

and try to determine the matrix UIHlk). To do this, it is useful to write q as


.

v'2
where a and at have the following properties:

a J =

=0

= VI Ii -

(2.5)
1) for i > 0 .
Consequently, the matrix representation of q in the space of the unperturbed
a 10)

and a Ii)

~ 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 nitedimensional 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

ields the Hamiltonian matrix

/ MatrixForm

(2.7)

1.
2

+ 154 ).

Its eigenvalues are

discrepancies from the exact result.

2. Linear Equations

50

8
7
>.6
~5

~ 4
3
2
1

~~

---

. ,..

Fig. 2.1. Approximate valut:::i lUl'

0.2

0.4

0.6

0.8

Lllt:

'"

luur t:ll-

ergy eigenvalues 01 tne quantum osCillator with the anharmonicity Aq4, as a function of A

lambda

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~~

mat
Ii
~

&~A

~ "" non h ....


~-

~~A

~~

'r>

.1

'S:

U ...."'U
~AJ

llu
".

~~AAAO

4o'h ....

.1 .

~AA~

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


= Sort[Eigenvalues[mat]]; Ii [[1]]

",h4o o'n

f t .....

~"''''....
'v

+'h ....

WAA~

~"'p

&~AA~

. AAAO

uo:>l ......'" ~"'''' ....


&~A

')f\ o:>nrl ....


'v

_~

Af\.

~AA~

&~.

(20) = 0.559146327396 ... ,


co (40) = 0.559146327183 ....
co

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\

ClO \ <j;U}

..... n .....
~ , .:)iJ ~

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

u. OJ OJ\} lOj

0.55914

-.

S
UJ

r'r'n1,.,

V.JJ7~J

0.55912

o ~~Qll
0.06

0.08

0.1
lin

0.12

0.14

Fig. 2.2. Approximate


values for the ground
state energy of the anharmOnIC OSCillator as a
function of the inverse
matrix dimension 1/n
forn=7,8, ... ,20

2.1 The Quantum Oscillator


T,

D.'

.......... "'0'

'l1
~

.....' ...

.1,

'-'

v ....... J

-'

,... u.

r.

.LVLU.

., r.

~~.~~... .LV.L

..
V"".L

'''-''-

51

rpl.

,.

.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

____

----

_==---------

'1-/

3
2
1

0.2

0.4

0.6

0.8

lambda

~lg. ~.3. The nve lowest energy eIgenvalues as a function of the anharmonicity
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 potent.i~J
AI
"%.

'-J'uc "au

"
CWOU

.,.

lIUC

r
U.L

'1

-'
CW.lU

'1

y.

pressIng the operators In terms ot a and ai, analogously to


this improve the results?

,1
LJ

L
UJ

l~.4).

C,A-

Uoes

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 comuter 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

= R,

= -.-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:
in
wing 0 ar e conserv i n,
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

...T.

IL

Ie

c::>
c::>

,.,

'1'I

'-'

'T

Yo

.LJ

01
01

Fig. 2.4. Series connection of reslstance ana ~v oscUlatory ClrCUlt

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

,-

VR - n lR,

laW.

Vo

~..I:;.u:)

1
:-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.... ') ~
0'

u.rO

h~"o

_1

_1

tho

_1 _1"

h"
oJ

-0

. . . If",

'"

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
n

'''-

I.o.l,u::

t"

.....

14-~~,", fnr thl~


'-'

'11.1 0 LWU

!:at thl~

Voltage addition: fa ( R +

R
r--t

J-

oJ

'T'hl~

iW~ + iwL)

+ Yo = V;

1~

"1

h"
'J

~OOOO'

l
C)I

Vi

C)I
C)I

~
,.J

Vo

......11:).
I:

--

-'i.i.J.

....
~

tlOn 01 .It--Li -lJ comoinatlon 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 voltages. In particular, one can expand any periodic input voltage Vi(t) with

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

Wn

eq1

= {vr

Wn

+ 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 sawtooth 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

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

or
1

Vi (t r ) = --

bs exp

.(8 - l)t r

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
= 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

sharper the resonance

omega

2.2 Electrical Circuits

57

-0.

0.5

1.5

2.5

0.5

1.5

2.5

output of the filter for

c
'0

>

f = 1 and R = 2700 n (right)

0.3

0.8

0.2
0.1

0.6
0.4 :

. :

OJ-L.~:~+4-+-.............-+-:;...++-0---+---;--1-1--1

-0.1 :

0.5

1.5

2.5

% 0.2
>

.
:

0~:------1'--~--+----:----t----1

1.5

0.5

2.5

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 network of series and parallel cir-

lon, 30n, and 90n

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


1

~ (Iz Vi + IzVz)
1

=-

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

w.

2.3 Chain Vibrations

0.2

59

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, Redwood 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
mt in

= 1 (t n + Tn - 2s n ) ,
= 1 (Un + Sn - 2tn ) ,

(2.17)

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

M- 1 F8 = >'8 .

61

(2.22)

This is an ordinary eigenvalue equation for the positive semidefinite Hermitian 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 pargously to the electrical filters (Sect. 2.2), the general solution can be obtained 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 vibration 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*Exp[I q]t Ot -ft

-f}t
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

..

..
..
e----

..
;0

e----

..

..

54(0)

52 (0)

53 (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

D (Ir - r 1 - a .) 2
J

V (r r)
J -- -2
~,

~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 apparent 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 investigated 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) =

(cos kxa + cos kya) ,

where a is the lattice constant,

40

(2.25)
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) =

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 ydependence of the wave function we assume a plane wave,

and with the dimensionless variables m

= x/a and u = a2 eB/ he we finally


m

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 number 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
(2.35)

'l/Jq/2 +r = -'l/J-q/2 - r = -'l/Jq/2-r

en-

o
Ao'l/Jo

= E'l/Jo , where

Ao =

.(2.36)

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.

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

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

(2.37)

2.4 The Hofstadter Butterfly

67

o
Ae 1jJe

= E1jJe,

where Ae

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


PI (E)

= Vi -

and Po (E)

=1 .

(2.40)

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:


is equal to

q
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
Pn

(E)

= (Vn - 1 -

Po

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


if( polyold*poly < 0.0 ) n++
fore m

= 2;

a) - e;

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 always 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 connection 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

(2.43)

10) ,

(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
= 0,

ctct

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)
osed to feel the

If two electrons occu


Coulomb repulsion

(2.47)

Unktnk.J,. .
,

,q

the magnitudes of the kinetic and potential energy respectively.

2.5 The Hubbard Model

73

= -t

(2.48)
k=l

with Ck+l,u = cl,u and CM+I,u


states, we choose

= Cl u '

For the order of the single-particle

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

c c

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 between 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:
twofold degenerate:

= 0,

= 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_

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 occupancy 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
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 _\

i:)IJaIJ'lJ

IY I

1". L
VI.

TT."

.J.1 ,L

.u

IJU'lJ

.,

1I..r

VVI.IJ.U .U'.J.

.J

1\ T

"% i:)J.IJ'lJi:) a u u J.

Yi

1\ T n '
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
.
11 nn<l \
roo.
1
.1.
oJ .L:.J. \
.L.L. " " . ,
tum ~ystems. lJomputers III PhYSICS 7:4UU
Montorsi A. (Ed.) (1992) The Hubbard Model: A Reprint Volume. World
Scientific, Singapore

T
TT
.LJU.L

rt

.,

,UaIJ.L;:)

T':'

T':'.

.L0:70:7~)

Y".

... Jr

.,

1' .

.LV.L

r'\,

3. Iterations

..

,.

,.

,.

Ul a ;:seL Ul
LIlalJ l:unven gIven InpUlJ valUeS lJO
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 computer. Obviously, one just has to apply the same function f(x) to the result
repeatedly. We want to demonstrate this with a few examples.
1"1.

U.l~U

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
U~

,.

..l

+1-.1'
' ..

,,~ '"

'-'

........

1".

..... v~

. .

A 1+1-.".......1-.
u

",
v~. . ~

"''''1' '-'J
" .... 1... .....
'"

....... 'V

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

.~
-

..l

'n t1-.o "n't

..

1 'n o:>n

.
.
. ,.
Ul LIle OlJa.l'Lulg Value Ul
'1'1-.0 00.

~,.

LU
the iteration. A well-defined function definition yields a sequence of numbers
that is practically unpredictable even for a small initial uncertainty. Such a
'

, ,

. .

1;:S

1::)

.. . .

~ ....

IPol

u,(;'1I(;.'

.Y

.Yc;

..

. .

quantItIes that can be calculated wIth the computer are not just
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
~ome

82

3. Iterations

We consider the iteration


X n +l

= 4rxn (1 -

xn )

=f

(x 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


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

Xn

can

then (3.1) becomes an approximation of the differential equation


dx
dn
with the solution

x (n)

4r -1
= -----~---

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 -

(3.4)

tS
'

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,
usin
such as f x_ = 4 r x i-x sim
iterf[n_]:= Nest[f,x,n]

The determination of the bifurcation


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
values this
2

r,

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


,.I",.. hl~.........

.
l' or t -

..,

_1

J .. " ..' 4....

rv Drv D

....... ,.1 4- l-.~~

" " . . " ' ' ' ' ' . . '"

........ ' 4

.... ~ rvD

rvDT D

"" .. "'.&oJ" ""

u ..........

UU

"-' .. "

,L
JUDU

85
D
VU.'V """.

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


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
. . .
.
.
.
:mcn tnat tne peaK or tne paraOOla in tne new system is at
(0,1). In this coordinate system, the original parabola f(x) = 4rx(I - x)
takes the form
.1,

ft\ -

JL

r -"

l:lnrl ... l:l ....O

II

"t 2

,-,,/

= r (4r -

.... "ll:ltorl

,,; l:l

= ~ (1 + viI + 4JL) .

2) or r

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

9R

~'fJ)

/1- 11

V JL

ana 9L

/1- 11

.1

~'fJ)

V JL

This finally leads to the following equation for JL:


I

= 1/V a + ..v/ a -

(3.9)

"fa

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:= per1odlnJJoin [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
1000 additional values of X n , transforms them into the y-coordinate of the

Xn ,

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
Xn

= 0.89 .... This is clearly visible in Figs. 3.3 and 3.4, in which 1000

values are plotted for each value of

T,

after an initial transition period

0.8

,....,

0.7

c:

~ 0.6

Fig. 3.1. Iteration starting from Xo


0.65 using
the parameter r = 0.87.
The X n values move towards an attractor of period 4

3. Iterations

88

I...

~ L-----------:t:----~
.:

~~m;

.. .;0; _-....

;;..,;;.~.

~~_: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

between 0.88 and 1

a parameter value T ~ 0.934,


just below the window with
period 5

90

3. Iterations

/
0.6

f\A
~.

0.2

/\

/
//
I

...........

./

0.8

/ \

1/

oV

0.2

0.4

0.6

0.8

Fig. 3.6. Superstable four-cycle


with r = 0.874640

/'
0.8

"

V
/

0.6
"

"

I
I

0.4

0.2

/~

\
'(

1/

0V

0.2

0.4

..

Fi~.

..

0.6

0.8

3.7. Three chaotic bands for


r = 0.9642, just above the large
window with the three-cycle

. .

. .

VI. LJUlt:) or .?~I II II


,(.'. I lSI 19 tne TTlPT 'lnrl~ or symoollc aynamlcs
are
and inverse iteration we find the R, with a precision of 30 digits, of which
only 12 are printed here:
-0;-

11 "'...,,,....

fl. ~

'.LV

Ru
R12

= 0.892486401027 ,
= 0.892486414339 ,

R.o

o on.n A 0'"'1.1 71 QO

li14 -

U.XUIAW";A

'~u

R15

1'(~Ul

= 0.892486417932 .

.1

3.1 Population Dynamics

we find the following approximate values for


~

= 4.669201134601

~12

= 4.669201587522 ,

~13

= 4.669201604512 ,

~15

= 4.669201608892 .

91

~:

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

..

.
....

.
.
..

.
....

.
.
.
.

..".

(\

III

.
....

111111111111

40

20

60

n...

.: &5. u.o.

80

100

precision of the calculation

rn1~

,.
~"

oUt::

VJ.

XIOO for r = 97/100 as a


function of the precision
with which the calculation
is performed. The vertical
axis e:ives the number of
digits to which Mathematica calculates the result of
the iteration

Exercises
1. Calculate the Lvapunov exponent for the loe:istic map (3.1) as a function
nf tho
n.
~.

'I"

r
, .

~11

~dt;11

,.

J11L~J

,1

VdJ 11J

, .

<..I'

L11~

L11~J~ dJ~

'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

V.lI,.LJ.lI,.lt"

rY~TT~

,v

_,

rY~TTT

auu v

r.
,-,Ut;;

r,
VJ.

LUt::Ot;;

.,_.,. . .
..-

J.O

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


three orbits of period five.

-,

---

Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Redwood 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
n
H r.! (1
. . . t:lHllnQ AnT
, oo~,., n
.,
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 segment 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
8x n

With the definition

this leads to

or, transformed to the inverse recursion,

(3.12

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

H MN = K

L
n=M 1

1
2

(1-cos27rX n ) +

(27r)

or gIven parame ers


h=

lim

N-M-too

N -1 MHMN'

2 (Pn -

u)

(3.19)

n=M 1

e average energy per par

lC

e IS

(3.20)

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 winding 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"

+ -21 (Pn - u)

(1 - cos (211"x n

(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 socalled 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. Quasiperiodic orbit in phase space

0.35

3.2 The Frenkel-Kontorova Model


~

0.05

I \

0.03

1\

I \

I \

I ,

I \

I'

0.04

1\

I \

I \
I

0.02

"-

I
,

0.01

}. J

\1

If}

-.,

1
&

\\1

\I

\ 1

11

Fig. 3.11. The same quasi


,.-

"1
~

.or

. ...

L1CU

~4-~4-~ ~~ : _ ...,:_

'> 1 fl

~u~u.....

.., . . . .

VLl

~~~_:

lIV'p

VI.

&0'

till"

,.-

~,

'1,
-

\;L; J

no

V.U

.-...

99

0.6

=
>< 04

'-'

n_
v.~

20

40

60

80

3.~A!:. Tne QlSplacement


(modulo 1) of the nth partide is plotted for the same
function as in Fie:s. 3.10 and
~'Ig.

100

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 =
. ..1,'
..
..1,'
nf h( 'r'~
~ !:llnrl tho
~
n.A. If tho .- .
, 'v'r v /
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
~

.....

I.

, ,
W ~ U)

PIn ;n otono
I~

Uc:G:5 aU

-.-

..l.Ll..

1.

_1

..

VI IS Lel'lS , aUU

n .

.:lIO

('1,

'~~U

v,
.

1"

",vU ..

&

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 competition 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
~&~ .....

&&'V'uv,

without changing their energy.

.J

" .... .,.,. 1.. n ...1.

v"-"&&

",v

~~

+1..n
U&&V

.-

100

3. Iterations

f\ f\')O

0.028
>.
tlO

0.027

~
o 0.026

0.025

U.U:l4

u.~

U .J

U.~.J

_.


U ...

U .J.J

pO

-!3
tlO

.5

:a

0.45

0.425
nA
v.

.5 0.375
~

O).~O).

0.475
~

Ig.

f\,

....
0

Jnergy 01 a
lOree-nee state wltn u 0.4 and initial value Xo =
0.0838 as a function of po
~

0.35
0.325

_. -

0.2

0.25

0.3

0.35

11::).

..

, ,

Ul:S-

O).~<:I:.

lianCe W OeliWeen neignboring particles for the


force-free states shown in
Fi~. 3.13

0.4

pO

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.'

K.

1'.

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 Weinho;1'Y1
.r<

u-

, l\TonT Vnl"lr
............

r .. ""'''''' ..... ,
~ .L::1::1U)

r-.

TF

.....

..

,.

.r<

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

'n->"

.n..D.

r r

Vi

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,
k ri
n w
I
I
I
f r'

,
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)

=-

lim ---"-'-

e~O

(3.26)

102

3. Iterations

e or a ine.
square an
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 wellarger 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
,

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

an

103

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}}

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, independent 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.

In M t _ I' ( -t) In 3 + In M _ In 3
-1m
--.
t~oo InL t
t~oo (-t) In2 + InL
In2

-_ l'

1m

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 creditworthiness 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 vectors in N-dimensional space. Equation (3.28) separates the outputs So = 1

shown that their number is less than


to 1030

2(N ),

which, for N

= 10, still amounts

scn e y
neura ne wor 1S supp 1e W1 ne! er ru es nor programs, but examples. In our case, the examples consist of a set of inputoutput 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

=.

3=1

-Xj

This method however


x

correctly by the current vector w:

(3.31)

3.4 Neural Networks

109

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

w* .

Zv

>

> 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))

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

(z v )

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

N
which, iterated from 0 to t, leads to

N'

- 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)

3. Iterations

110

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

= (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 Rosenblatt 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[O] = inputj
} /* end of while */

= neuron[i-1]

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 predice 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 characters 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
TO

3. Iterations

..................

Hertz J., Krogh A., Palmer R.G. (1991) Introduction to the Theory of Neural Computation. Addison-Wesley, Reading, MA
., ,
n
D
A~ T~+_~
1\ ,r:~ 11
l\If 'T'
.1 "'T
.......
..... 1100t::\
\ ... .,.,.." .
...,-u .........
.
......
, D , , T uu..
auctlon. ~prmger, tlerun, tteiaelOerg, !~ew lorK
..l

. \AU

.... ,

1\.T

_AAV.~

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


s

First, we want to discuss the solution of an ordinary differential equation.


n

y(n) =f(x,y,Y',Y", ... ,y(n-l) ,

,
obtains the following set of equatio~s:

(4.1)

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
Yn

= Yn+l/2

Yn+l = Yn+l/2

- -Yn+l/2

2 Yn+l/2

+
+

(h)
2

-Yn+l/2

II

+0

II

+0

2'Yn+l/2

h3)

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
written as

J depends only on y

and not on x, then (4.11) can be

.=
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
... ......

....

fl'\

rl. __ ..: , ... __ _,

;.r...

_1'\

rl. __":' ... ___,

1.

r._" '''' ."', '.;.'''


...~"
"t'....oAoV.t'V", ""&U"'A, ... ~

"'1'1''''

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

1.1.'
thA nlnt nn tho riO'ht.
,
-, ]:;'nr
v
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
Tl'llH:!t hA

.,

, (QAA ]:;'i 0'

-I;"

-0

i~ not.

:mn t.hp
ru:
'-'.I

..-" .

W'V Lo....L

I;"

't'lT_

.1.1

-l-l

'Y'V o.uu

L_

a.

_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 '\

,/

0.5
0

-.........

1.5
1

\,
J

-v.,J

-1.5

-"...

'A

-1.5

..."

-1

0
-v.,J

~ ~

-1

"""\

,7

0.5
p

-.........

"

- ...

-A

"

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

""

/.....////..-

0.5

-.....

~,,"\..'\

11(1f~~>~\\ \

'.11

-0.5

-I

\ \ \ I\I\ \\.~ W / / J j

~~
"---,.

.-/

~~

~~

v.v

",-,.J

.
A

~.

A.v

.r II;'

~.~.

......
J.

1l~

::5i:J,1~1~_

.,. .

..

a<:I
~

snown on tne leIt-nann ::51U~ UI


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 Pern ro
pnnger,
oer ., u lrsc
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 =

(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.

or r > ,pOSSi Y ter sever


re axes to t e rest position cp = ,w =
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 ,

smcp = a cos

cp

Using

(J =

Wo

wot we obtain

cp = w,
(J

(4.20)

Wo .

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
i

and the information dimension DI is obtained from


Inc .
Now it can be shown that the following relation between the three dimensions
holds:
e-tO

c
In practice the three dimensions often agree within the experimental error.
m

To solve the differential equation (4.20) numerically, we choose the fourthorder 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
e s ep SIze reqmre. n ou pu, e vanaccuracy, an t IS an es Ima e 0
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"

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

+ 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 probability 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 eficient 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 function '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

energy E8

EO

AX 4

+ 2E) 'l/J (x) = 0 .

= 1/2, EO can only take integer nonnegative values,

=n !

analytic at A = o.

where n

=0 1 2

... .

(4.29)

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)

n, i.e., 1/1n = 1/1(x n), 1/1~


the Taylor expansion,

(4.31)

= 0

= 1/1' (x n), and so on for the higher derivatives. From


... ,

we obtain

For

1/1~

we can substitute

1/1~ = - kn 1/1n ,

(4.34)

derivative by the second one in its discretized form:


(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-l
to change the values of x, y, ym! from within step, we have to pass the addresses of these variables, each of which is marked by an &. Note that in C
n

e argumen s.
With this, the calculation of 'l/Jn+l goes as follows:
double step(double

double dx, double *ya,

xml;

xml=x;
yml=y;

(1.+dx*dx/12.*k(xpl;
x=xpl;
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

[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.

...;i,.....~....

4.3 Stationary States

135

energy elgenv ue

Exercise

Literature

erSpringer,

136

4. Differential Equations

So far, we have only considered differential equations for functions that depend 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.
e

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
0

.........

\
-2

137

,.-..
("t)

q -4

Fig. 4.8. Two solitons

'-"

=='

move away from one another. The numerical solu-

-6

.J: .J

\ ... .., .......

';"'~ ~"I

I
"A"VAA

'C'.J\.CIo'..".

-8
-10

-5

(in::

10

VU'C'

(t = 0.3, dx
0.002)

l.'161

\ I

guuu

111

.1 ..1.

,......A .....

" .... ~

Uf:-J

"V

= 0.18,

dt =

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

1-. nn 7\T '& & ~....

~.... ,,~

.... '-'......

_1 . 1.
.,. AA.......AA

,,~.n. ~n~

+1-..n.

'-'.LA.....

"AA .....

..... .......L

.1

,,~+1-.. .....

'-'.L

"AA.....

V ...nT
... ....... ,

equation by using the methods of inverse scattering theory. Since the explanation is too complicated for the scope of this book, we refer the reader to
tho ,.

.1"

'" hn"t

Algorithm and Results


T.

~""v"""~"

"V

.1

.11.

"v,,\'~

.1.

".... ~

T..... .J't T
~t.. ....

"

&

I A

ll)"'" J'

\ "'%.<1,

YV~

......

,.

c.
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
au
au
1 ( .
")
~
(u i +I -ui )
(4.42)
--+
--+
dt
U~+l
u~
,
dx
n
n
at
ax
By applying this rule three times we obtain
.n.

.n.

..q3 ..
'-'

- 3 --+
aX

(dx)3

(u 3+::i _ 3u3+:.:l
n

+ 3U3n+ 1 -

U3~)

(4.43)

With these substitutions, we solve (4.37) for U!.+l with the result
,

,;

U~+l

u~

. U3+ 1 - u 3
+ at I ou~
dx

u 3+::i - 3u3+:.:l + 3U3+ 1


(dx)3

u3 "
t':l:':I:4)

4. Differential Equations

138

......
.
.lImS

..

..

, . ...
,weJ. -c
tU-;"Jj 0
by a list with max + 1 elements. To initialize it, we use (4.39) with N = 2:
~41

IS

C;a0:3 U

.y

III

rlIp.

'J

ustart:=Table[-6 Sech[(j-max/2)dx]A2//N.{j.O.max}]

and

..:I.'

~~rv

1.

l'

We

the

1''',

1i~t~ I'lJ.j+k).

,~

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
........ ...:1 ...:1+ -

{\

. . . .A A ~

'V.'V_

~v

= 0.05

{\Il

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 oscillations, which are caused by numerical inaccuracies and "explode" after just
.
.
. ,.
"."

lIWV

UIVl~

A-

, Ii:)

.L lUi:), VI

~A'V~

dllU l;dll ut:

. .

Vll lIUt: UCLU

algorIthm.
What went wrong? We have committed several errors, which we can avoid
by the following modifications:

. .

_1.
_1.
_1.
UJ.l' lIJ.U:;
lI.1J.tJ
tJJ.J.UJ. 1..11. lIJ.J.tJ
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.
1

TI'

.L.

.u.y a.

'1.

l'

....... 1

--

~~,

-5

><

='

.&_&_

-10

-15
-10

-5

0
.,

10

Fig. 4.9. Integration usmg step[u] and step


sizes dx - 0.05, dt 0.02. After just three integration steps, one obtains an unphysical re",.. 14-

_.'

n
A

'T'l...

_'1.

..l

_1_,

--~

.1.
U&&&'"

U.
UV

... & 0 '

A 0
-,,;v

4.4 Solitons

Ul

139

= Uo

Then,
dx
1 -

-I

2dx

(4.45)

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-

where we have already substituted the improved version (4.45) for


Solving for the components (U~+l,U~+I' . ), which we combine into

..

a/ax.
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

- - - - = -va
dt

eikdz

e- ikdz
(4.50)

-----

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 -

(4.52)

This ives us

Now we have

j+l _

j-l

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

n+

i+l _

j-l

vdt . kd
= - 21 dx SIn x .

. kd x
= - I. -vdt
SIn

be chosen to be sufficiently small compared to dx.

(4.57)

(4.58)

4.4 Solitons

ax
U

8x 3

141

2dx

~ !3 (u in+1 + uin + uin- 1 )


---I..

--r

2(dx)3

3+

Un

3+

Un

+ 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 solitons 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

-0.5

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
large one is accelerated in the pro-

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

....-......

()

'\.

/"\
"-/'

-1

4.4 Solitons

143

c;) _,.

q
-5
~

-3

Fig. 4.12. Results similar

-4

L ,.

. ..

an
-10

0
x

-5

10

...".

~.

,.

. !:i{,a{,t: '(1,\,x,

bV bUVOOlJ &U

.I: .If) "%.0, UUb &VJ.

Inn,l~

-~

U) -

seen' X. In aaWtlOn to
the soliton moving to the
right, waves are radiated
-q

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

"'

..

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

~3A .
~A.
..., ....
..., ....
- -- - 8x 3
8t

(4.59)

The discretization used here yields

u n+l
J

--

u n-l J

rlf (",j+2
\ n

,>",j+l
n

..L

,>",j-l
n

(dx)3

",j-2\
n
I

(4.60)

Investie:ate the stability of this ale:orithm by usine: the ansatz (4.49) in


,
, tn (L1 ~7\ thiCl lO!llrlCl tn tho
,. ,
(L1 I{O\
th!llt
,
,
..
,
.....
T"\

-J

.~

.
1 2idt [sin (2kdx) - 2 sin (kdx)]
a=-(dx)3
a

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
dt

< - (dx)" .
p,

(4.61 )

144

4. Differential Equations

,
mine the stability limit with respect to dt, for a given dx; i.e., approximately determine the maximum dt allowed as a function of dx. Confirm

Literature

Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Redwood 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 suddenly 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

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

tf;n (x)

=n

1r ,

were

= { y'2 c?s (nITx)


y'2 sm (n1rx)

for n odd
_1 < x < ! .
for n even'
2 - 2

(4.67)

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 attention 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 overall 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)
correspon
hand, with

W lC

+0

dt 2

(4.83)

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

_
If''n+l -

1/J~+1 =

i "I,i

If''n+l

+ tr1.1n

(4.90)

-1

2 + (dx)2 Vi - i (dx)2 - ai

solve for ai and ~. The result is

1/J~+i + ~ - {}~

(4.91)

150

4. Differential Equations

~ = f}~

iJ!.-1

;-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

tPn+l

(.

2 (dx)

dt

- (dx

)2

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

"

n ,

151

{~} 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

XQ

= 2 /.' sin (mrx),p (x, 0) dx .

(4.101)

= 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 nPh

v~

for this partial wave has the value

= 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
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 moveand 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.

Wn

J
Itf;~'1
Lj=J/2
J

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 l"U Ule L Le ---t

---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 simulate, 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
. nr.p..
r
. .,
, 4.,
.,.
1..
u.
.4- 4.

~,

.L.L'V.L'V

n'V

......L.LlJ

lJV

UO'V

-.L

lJV

&

OlJUUJ

....v , y

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&&....

-,

..

:h", +l.", ,,; .........,.,


U&&~

."u,,~~

..

.... + .....l. n " " ,

.... u

n_",

U-L

&

"~

....-L

+l.",
u .... ~

_.

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

...... A&~

~"' ..

-L'U'''

..............

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.
.J
,. , to .
i .P.
..
.. ..
.. rI~.t.~.
and generate output data. Therefore a computer acts like a deterministic
function that leaves no room for chance. Still, there are algorithms that gen,
.,
. . ., tp~t~ ~l1rh~.
p.r~.t.p. "
Tn Tn~.nv
of
.. , .J - .J ,"
., .
,
.,
.,.J
~..J ,f'.

"

.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.,

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

rand

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
m
rndm[r_]

= 1283

= 6075
= Mod[a

r+c,uU

The following command turns the vectors en into graphics objects and displays 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]],

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 periods 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:

is positive, and to

n-s -

n -

Cn

= 0 otherwise. The first

n-t -

n-l

value needed can be set to 0

5.1 Random Numbers

1~

'"

~fO,

T T.

i:uu5.....

~_

,.

l.L VJ.U

161

, .. "

l'.

,i:l

lJUcuJ. J , lJUC

_'"

LJ

values of s, t, and m for which the period can be calculated. For example,
the generator
r~

,~- r . .-:1

(r.

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 automatlCauy 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).
thp'

no

,1

1
<J

f".1
V.L lJUC

127

about 2

.~

.J

nf -'-

hun

.....

".

J.., lJUC

::ITP
......1
,J;"

fO .1.

,1'

V.L lJUC lJWU UJ.UJ. v J.uuaJ.

Therefore, this generator can run for about

1024

thp

'.".1 '" 1 1

.1

.....

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

(x, t

+ L1t) -

u (x, t)

1
2d

2d

(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

L1u = r d - 1 ar r

u(r) =

d-l

(5.13)

ar u = 0 ,

(5.14)

UQ

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 partid-2

equation:

(5.16)

d-l<D<d
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 aggregate, 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 simulation 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;
J

ry=rs*cos(phi);
}

5.2 Fractal Aggregates


...:11

169

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;
,.. .........

'J

"oJ

.,

. ..

':t ....... ~ __ 1.

'

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 ,\

Ar

,1

lAnl1" "

!ll

U/

'0

"

(J:/
\.

'> fl.\
U/

-'I

tA h.o

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;
... - ..'1.....

._,
LL

.. J
,

,A'"A'

-, t

"J'

~~.

A t
if (r >= rd)
return 'c';
if (xf[rx + 1 + lmax/2][ry +
xf[rx - 1 + lmax/2][ry +
xf[rx + lmax/2][ry + 1 +
xf[rx + lmax/2] [rv - 1 +
return ' a' ;
else
return t j , ;
\.L~

."-

,~

... "" ........ u

lmax/2]
lmax/2]
lmax/2]
Imax/2]

+
+
+
> 0)

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
.., .. , _ ...
.~,

.L'"

___.

In
...
.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
case
case

;break;

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

Pc or 1 eren
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
1

V,

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


v
~ '" Ip - Pcl- .

diverges, and close to Pc we have

(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
defined in (5.19). In doing so, L is measured in units of and M in units

e,

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,
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)
L D . Thus one can numerically calculate the fractal dimension
D from the increase of the number M
L of articles in the ercolation
?
tv

,
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


11"(0, L) = 1, this leads to

= tr(l,L)-

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;

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 generation. 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 ++)
r....1__r,. _11 =
rn1r-i1=
r.. 1rn1=
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
f nr ( i

-~-'-_.-

-~-,._--

--

-~_

=~.

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 )

-_._--",.

,\

,. 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
,
. ..:I _.I: .: _ .: .. .: __ ( .: .: \
., .
1.
.J
~:4-~~
'T'l..~ ,.
l.... .1'J

............ .&.......&. .. .&."'..... ,.&.'J'

.&. &&v

U&uvu.

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
c~NJ:;U
)
1;[ \ array L1J LJ -lJ ==
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

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 properties and structures as simply as possible. One proven model for this is the
randomly generated path, which is called the random walk in scientific literature. 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 rearded 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

(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
D=--

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 erence 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
simulation is

IS

184

5. Monte Carlo Simulations

(5.40)

There is, however, an efficient method to directly generate polymer configurations 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 characstep a ter t erst one IS to tee ,strrog t a e ,or to t e rIg t, an correspondingly 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
uration on the lattice labelin the ends of the chain

1.
... ",-,.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 reptation 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 terminates 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 generated 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.U.ll L.LJ A,

L"J A -

direction[2].y=-direction[l].y;
r=random(3);
return direction[r];
}

The function intersection(c) returns the value 1 or 0 respectively, depending 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',

ft.

V&&....

U & v ....

&U

....

~.

' .

V&......

&& . . . . . .

& ...... ~""

~&&""

V&& ....

are
oy l;ne v(Wut:; ~ncr. un l;ne
, l;ne . .
al; l;ne lOcal;lon
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
u

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


'or'

oJ..

..

oJ ,

&0 _ _ -

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

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 system. To this end, we consider a square lattice whose lattice sites are occupied

H = -J

L
(i,j)nn

SiSj - h

L Si .

(5.46)

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 theorem, 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
avera e

--? 00,

tl --? 00, this time average agrees with the statistical

(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 random 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 --

!kB

2 269 J
~.
kB '
In v2 + 1
2

(. 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
e .
e v ue 0 e IS on y v 1 or
more wea y an any power 0
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. Asymptotically 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
vd+ a v

d-'Y/ 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 energy barriers. The Metropolis algorithm, on the other hand, is simple and

any arbitrary initial state, since the system always relaxes into thermal equilibrium. 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
,
4
40
kBT = J, to ~ 10- s), therefore, we obtain T ~ 10 s, much longer than the
universe has existed. Consequently, we will not be able to observe a reversal

. Igdl'ill fen'cmlagnet:
~lllli~N .. , .
tflmpmatum T"O.39T~ ... ma9n~ 111"10.041

Fig. 5.11. Diffusing domain walls of the ferro-

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 fluctuations 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 u3. 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

= (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 ,

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.

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)

Eo>
-LVii.
-2

(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


2

205

6
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

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


l1n;f

Tf "",n ho ~1

.1

~1 ",f fho

.1".

1.
~

Af

fho

'0'

-,

207
.1

fA1"
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

.,; _+
'

............ .,; _+ 1 .._'


-,
r

.LUI.

.L'J.

memcpy(np,op,N*sizeof(int;
j=len;
for(i-O;i<=lenji++)
{

np[(pos+i)
j--;

Yo

N] = op[(pos+j)

Yo

N];

1.
"\.
.J

The algorithm for calculating the path length is obvious:


double length (int path[]

l.nt l.,j;
double l=O.,dx,dy;
for(i=Q'i<N'i++)
.(
-i=(-i-&o1

"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)

Additional functions called drawDath and Drint draw the oath and write
fo.... + +". +1-. .....
v~

V"

VAA~....

.1.
.L

l:i:LH mse "He

.J
..

..

~AJ'

.L-

1#.1: CI. v t;; l. ljO

'~u~""

.,. ,,... +1-.",

A 4-"+",...
4

. . . . U~ . .

ljIle

A.

on ljue

U4"~

..
ana

1"'A " b A ~".LA

...'"
~

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
A

~4-

~4- 1-

1
~

L:JUu..LU

n .. u ....

u.

P from f.~7R) h~~ thp V~.111p P ,..." 4.R WI"


'.
1- ~'L
.1-

... 1-
In
D.
...... .... 1 v .LJ v ......... au " ......'"

..system quickly relaxes to the value l


4-

v .......,J

...... 0

....

'r

.....

".........

2.2, with about 20% of the attempted

208

5. Monte Carlo Simulations

Fig. 5.13. Randomly generated initial 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

..

L.l.l~

.l::S ollaJ.lI\Ju W.lL.l.l

U.l.l

..

..

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
.,
. arp .1 int.o
.L.
Onp pnr1~ ~. J I .. .LL
in t.hp ~~.mp
,
, -.. .... rnL
.
...
TT.
.L
T. r
r'1.
T"\

_. .

systems accomplishes the same thing.


YV 1.111.1.

~.U

0 o.J 0

.I.. J.J.\J

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
&

...
..L 1
r:L.I.

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

Ii'

in L4J : - :;& II
Out [4]= 3
Tn r.':;1 0 2"-:t

al,Vl,sl,on

I -

"

DutL5J- 8
In [6] := (3+4) "2-2 (3+1)

-.. Ai
-n.. +- .f1:1In [7] := %/5

%= the most recent result disvlaued

212

A. First Steps with Mathematica


41

UutLIJ= -;OJ

In [8] : = N [%]

= numerical value of x

N[x]

Out [8]= 8.2


Alit::.

T'nral.-??

n?':l

1n"'?':l\

Out [9]= 3.71908 10- 23

Order of precedence: power before

In [10] := 3 "'-2*36+'
n,

rof

"'"1_

The Most Important Functions


In[ll]:= Sqrt [16]

Sqrt [x] =

-IX

Out [11]= 4
~J.l

L .L.&.J -

......

L ~ ... , .. J

II

P"

L:L

= 1 h70A
In [13] : =Sin [%]

Sin [x]

Out [13]= 1.

1.

JVI". VJ/I

nut- f1?1

= sin x

= 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
~

.. .

..

= cos X

In [14] := Cos [Pi"]

Cos [x]

nu t; r 141-

p.T.f1r.t 71f1I'IJ.p.

1
Sqrt L2J
In [15] : =Exp [0.5]

Exp = exponential function

Out [15]= 1.64872

numerical value

In [16] := Log[%]

LOJl: [x]

.. ...
UU"'(; L.LOj- u. 0

= In x

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 ....

Out [17]= 0.5

hD

-"~

In
-- -J

nnn .....
~

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]]
Re [z] = real part of z
1m [z] = imaginary part of z

In [20] : = Re [%] +I*Im [%]

171

ArcCos ArcCot ArcCsc ArcSec ArcSech ArcSin ArcSinh


ArcTan ArcTanh ArcCosh ArcCoth ArcCsch
In 1 := ArcTan [1]
ArcTan x = arctan x
Pi

Out [21]= -

In the following we will omit the input and output designators In [ .. ] and

Parametric
plot of a circle. An ellipse appears on the screen because the axis ratio is not

ParametricPlot [{Cos [t], Sin[t]}, {t, 0, 2Pi}]

,
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]

A list of the options available with Plot [ .. ].

Options [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

(a+b) A3

0.2968512129099, the number a to 13 digits. If not

---t

A
f[x_]:= Exp[-0.2S x 2] Cos[4.S x]

This is how functions are defined. 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.

215

A. First Steps with M athematica


r

.
J .".'" J
--'''-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}] .

'PII'I _ ...

I:

r '1

'PlIO:

... 0:

Dl . ~

'I

_ - - . - ..... ' l.. '

~J,.

..t

... .",.,

..1-:

.t.

.c.

..J

..J

,J.

Plot[{fermi[e,lO], fermi [e,Xnfinity]}, {e,O,1.7}]


two Fermi functions. Infinity = +00 .

.......

n-

.-

1.

ov'Vu

'V'V

..J

........u

..J

A function of two variahle.~.

fermi re_.b_l := l/CExnrbCe-lll +ll

'TIL

.1-

~~~~~

Plot of

.1

UJ

&

a..<"

&

a = Random[]
The right side is evaluated and the resulting random number is assigned
+,." +l,." ..."' ...; '" 1-..1" _.
_ ...., 'V"J ..
u'V
U'V

+,." _ ..n;l1 ...;,,1..:1 +l,.;" ~ .........1-.."..

t'

u'V

.,.

'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

A list with three numbers. Lists are written in curly

numlist = {2,3,4}
braces {} .

.. r_ _'1

-.

.: .... ,

numlist"'2

--I.

r ..

,",,+

..

'1":'1

----.

~~~

....._ , .. '""+
_

..J

.,

::J

",,'" "
'V~_

J.

,;",,,
1';",1v_
vv_
~

{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

Table [i"'3, {i,S}]


.........' .... r1/.;
.. . 06.

.1.;
l06

":t

{2,2,2,2,2,2,2}. Table [ .. ] creates lists.


~

..J.
Dl.,

Table [x, {x,O,2,O.2S}]

{1, 8, 27, 64 , 125}


--I.

J.

J.

J.

J.

J.

J.

l3 ' 4' 5' 6 ' 7 ' 8 J


~

{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

( \ !:lftor !:In

..

\. f

tho nov+ n,,+

......

. 1.

Tn

spite of this the variables have the assigned values.

L15'tl'".lo't L J ptOtS (UStS OJ) aaw.

1I1S'C~J.O'CLJ.1S'CJ

letters

= Table[FromCharacterCode[j],

J..n .I- .....vV'


~ln~

~a.b.c.d....

--+

Sortlettersl

{j,122,97,-1}]
--+ {z,y,x,w, ... }

1. Sort r.. 1 sorts not onl'll letters

J.

v ... .,

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

. .

J.))

--+

:l.~b

J.1St [[:lO,:l))

--+

1. ~IUr(

= Reverse[letters]

abc

. .

"

'U, we tengtn OJ we USt .l15't .

--+ {2.95, 1.91077}

list [ [20] ]
J.1St [[::lO,

----?

abc [ [-{ 2 , 41 , 6 }] ]

--+ {a,b,c,d, ... }

--+ ib,d,f}

--+ z. A negative index corresponds to reverse numbering.

abc [[-1]]

Pe~utations[{1,2,3l]

--+ all permutations of {1 ,2, 3} .

Storing, Reading, and Fitting of Data

.....

._rn ..... _'-_ ..... n'


I.

= 1.0

[x_]

x"41

fll~~_n ~11 n~l./ J . .J::.


""'."'.... , v

......

-.I

-"

J
v .....

J. J

~~A L

.......... J

.Jo"

,n

2.0 x"2 + 0.5 A fourth-order polynomial.

--+ the definition of f [x] .

?
III~

.I

..

......

..

.. ___ LoL LA.I ,

1. A,

..

..

_'I ..

'~. ~, ~. ~ J.I

Random[] (without argument) rer:= Random[Real, {-0.1,0.1}]


turns a real random number between 0 and 1. Random [Type, Range] is the
m.nrp

.1
v

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

dat.a list. .dat.


filename.

217

Objects in Mathematica can be written to a file with


zng

!!list..dat.

zs comman
dat.a2

==

dat.a

OUt.put.Fo~

==

True.

! !measured. dat

is the logical equality operator.


measure at.

measured. dat could be a data file that was generated

in an experiment.

model [x-l

=a

+ b x + c x 2 + d x 3 + e x 4
model function whose arameters we want to fit.

Needs [Statist.ics'NonlinearFit' l
package NonlinearFit.m .

Simple Mathematica Programs

We define a

zs comman

A. First Steps with Mathematica

218

(.* Th1S 1S the Iormat Ior comments 1n Mathemat1ca *J


Clear[" Global'*"]
f [x..] : = Tan [x/4] -1
.....
...
.....
r
r .LOl;; LI LXJ , t X, L. , &t JJ
r = FindRoot[f[x]==0,{x,3.1}]
pi = x I. r

(* clears old definitions *)

rwts r lXJ ana returns me vatue ~. 14_:>~, an


FindRoot r.. 1 finds numerical solutions of eauations.
8.88178 10- 16
~

program.~.m

afmroximation of 1r.
N[pi-Pil

(* 3.1 = initial value *)

The next nroQ:ram stored as Droll'ram2. m uses the M athematica function


n, __ r 1 ... ~..1

~
~
",f: .}.,. .... ro.
T (~\ T
1~

.}.,. . . . .n. . . . . . "'. .

,1

...

.."

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

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'

..

1:'':

"

oL .... ~'W

-,n

f.t: f '
-

_.n

v, l( .... ' ..............11


J.",

"oL ...... ."

zero = x I. rule; list = {zero};


While[Length[list] < k,
rr
----LL
-....
---........ . -,
.....
rUl.e = r1naI\OOl;;LILXJ--V,tX,Sl;;arl;;JJ;
,

0; .. +

_1 1 1

..L

no;

zero = x I. rule;
AppendTo[list,zero] ];
If[n> 0, PrependTo[list,O]];
Plot[f[x]J~x,O,list[[-l]]+l~];

list ]
~~

- -

'L

-m

r":t

"

41

--4

PInt nf

T.'

.T.,-,( , and a IiJlt nf


. thp ..fir.flt ..fn'll.r 7.prn.fI nf..

J3 (x) .
........ ,1

T
'I;

-~.-

,.~

-"

Do[Print[R Hello World Rl,{20}l


screen ~u umes.

Writes Hello World to the

219

A. First Steps with Mathematica

T.nnnQ
-

Do [expr, {iterator}]
For [start, test, 1ncr, body]

.L----'
...

...... ..

..!I.

'L

_.

_.I

Nest [2:, expr, nl


NestList[f, expr, n]
FixedPoint[f, expr]

... -

""'..

.....
, ""'..

..

,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

the numbers from 1 to 10 and their squares.


...
r 1 ~ n A.\
.= I . = -- .
~
n".,
tAnll'; , .. r'"
. 'D ....;n.. r.11
tween 0 and 0.8.

,1 ;all

lienerates

..

---

&.

Nest [Sin, t, 3]

~.~,

..

n.:;

~UJ

.J

.(n'l,r

hp-

'L

Sin[Sin[Sin[t]]]

- ---

I' D'- LD;LU,

-J

, uu"

In",

1;"t:1(""t:Ur ,.)v

UruUr

W1;",,,
,I

,I

,,"'t:

value 1.5.
NestList[Sin, 1.5, 30]
I

.j".,

thp

n(
-

numerical value of cos x to 18 digits.

f[x_]:= N[Cos[x],18]
FixedPoint[f,1/10]
II

\.-U;:);L,

I'

I'

NestList [ .. ] yields a list of all values cal-

thp .

~
,

li.e;., ",.e;;L JUI

\.-U;:);L

0.739085133215160642, the fixed point of

;L c,u

rr

~l.IIJJ

......... l.II, ...... y.

If [Random[] < 0.5, Print [Onumber < 0.5]]


beep: = Print [11\007 11 ]
~I:L.Ka

LJ <

.~,

beepbeep:=(beep;Pause[l];beep)

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

integration with Nlntegrate [ .. ] .


A doue imits

Head [series]

---+ SeriesData, a Mathematica object in its own right,

not a polynomial.

Timing[Series[Exp[Sin[x]], {x,O,80}];]
Null}

---+ {11.54 Second,

Vectors, Matrices, Eigenvalues

= Table[x[i],{i,3}]

Matrixl'orm[b]

---+ {x [1], x [2], x [3]}

---+ the matrix b

IdentityMatrix [3]

---+ the 3 x 3 unit matrix.

A.
-.....

yieLas me transpose OJ
__

'L

r ..... '
L-"

............

T.

221

First Steps with M athematica

1.

1.

... "oJ

"..,

.,

......

r'L ,

..

T.

LLlJ

Det[b]

--+ the determinant of b .

voor

---t

boov

--+ the matrix b applied to the vector v .

bood

--+ the matrix product b times d .

me scaLar proauct OJ v ana r.

booJ:nverSe[b)
the matrix b .

--+ the un'tt matnx; Inverse LbJ Y'telas the 'tnverse of

Eigenvalues [b)
"'t:'

'V~

VJ

..1

il.

....

--+ the eigenvalues of the matrix b . They are the


. J.

..1

"n", .... -v, u:-,

I:

'

'07

I I .il.

.1. '.1.

,-,un

.J

. J .i

r J.

U/"",,,

bin;

l;araano formUla.

nb = N[b]

.-

--+ the numerical approximation of the matrix b . The exact


.1.

.J

...

nrp

. J

h'l'

..1

r,.,'h 1 ~ [() A7f\11Fi.


of the eigenvalues of the matrix nb .

'III';

., "Aa

u = Eigenvectors[nb]

.,
()()I'\L!A,.,. ...

nf 10- 16

"

')l

J,j "f

--+ a list of the eigenvectors of nb .

-\oLJ--J

-.- L

'I1l9.th nn

() 04()Q()4Q , ()

_. -\oLoo ..

.1.

oJ

'. ""u", fJoAI,

"7

",n::.

I."""""

,.

~J.

".",(..c; "16C;.,

'"

uJ

nb are orthonormal, except for numerical inaccuracies of the order 10- 16 .

Sort[Thread[Eigensystem[nb]]]
J

tn thp ~~~
.,

J.

oJ

oJ

--+ eigenvalues and associated


.J~ nf thp.

,':-1-

.,

"

.J.

'DC>

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}]
"'t:'1

v .",

~'"16t:' , U",!/t:'

'~

--+ a smooth function which has a

...."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}}]
Th.9.(l

Tf nnp
"

..

r-

-"

n .(ltnrl .

variant of the secant method is used.

_J

.J

nf nn

"

'. J

.1A ~

A. First Steps with Mathematica

222

.....

...!!II-

.&.

_...

'I ...

L ...... g

60

--

r.

1.-'

......g ,

.ft. 1

J:!.

..J.

u.uuo

_VfJ

.1

Solve [eqns, vars] tries to find exact solutions.


NSolve[eqns, vars] numerical solutions of algebraic equations.
'I'

--- -..--, -.... ,..


-

.I
.

,, ___ r_
'"'

...... '"

,..~

......,.. 'V... " ....'V "'J "''''V''''''''''''

-.......-

..

....

l..

DSolve[eqn, y[x], x] solves differential equations.


NDSolve [eqns, Y, {x, XIIl1D, xmax}]
finds numerical solutions of differential equations.

Solve[a*x~2+b*x+c==0,x]

the 2 solutions of the quadratic equa-

tion.

--* {{x -> Sin[a]}}

Solve [ArcSiD[x] ==a,x]


A

Solve[x S-Sx 2+1 == 0, x]


NSolverx~S-Sx~2+1
~.t .f.J.':A

VJ

.~.

", ...... ""1

Too difficult.

-= O. xl

5 numerical values for the zeros

DSolve[y"[x]==y[x], y[x], xl
differential equation.

D::iOJ.veLY'LXj==\;OSLX*YLXjj, YLXj, Xj

the general solution of this


~~

lV 0

success.

NDSolve[{Y'[xl==Cos[x*y[xll,y[Ol==O},y[xl,{x,-S,S}l
a Mathematica obiect called InteroolatinfzFunction .

rX..l = vrxl /. %
This is the format that is used to convert the object InterpolatingFunction to a normal function which can be plotted with
f

Plot[f[x],{x,-5,5}]

Patterns, Ordering, Sorting


Remove L"GJ.ODaJ. * . j
-

~1St

t~,

;&, :l:la), golD), x D, :l:LDJ,

PositioD[list, f [_] ]
. ,1 .
fr

:J.", 51nLPJ

;&}

{{3}, {6}}, a list of all positions with

"

Cases [list, _~ 2]

Count [list, _~ -l

n.1 . . . .,.. r1.; ...


"

r .... ,

.1.'
oJ

616

LLI.J

all cases with the exponent 2.

2, the number of all cases with any exponent.

rhll
.

Ull <:.

{Sin[p]~} ,

,. .

--+ .(1 ?
.~

"

r~ 1

yn

r.

~ 4 ~i n -n l:ll
J

amdi.'lt
~

A. First Steps with Mathematica

. ..

......

"

__

'

l ....

'-J'

yzetas ne vame True. 1 nere are more nan


which one can pose questions.
? *0

.:)U

.
Juncnons

..........
OJ

"'fL .J

ne Jorm *l.I wztn

~ all these functions.

Select [list, NumberQ]


logical value True .
,...

u",,, ""''''''v/,,,

223

r ..

.L.

{1,2,3.4}. NumberQ[numberJ yields the

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.

- -

......
r

..:I

'

. r.L r:

..L

..,."".

Factor [term]
~ the argument of the function Expand[] above. In
some ways, Factor is the counterpart of Expand.
FactorTerms (term]
Co~~ect

(term, y]

l'actors out numencal coeJ:/1czents.


::jorts accort1f,ng to powers oJ y.

Coefficient [term,x"2*y"2]
Coeff1c1entL1st (term, xl
ofx.
Apart [ 1/ (x'" 4 -1) ]

~ 2, the coefficient ofx 2 y 2.


the hst oJ the coeJ:/1cf,ents oJ the powers

~ 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]]
.,.D,.+

Nowitisco~

~'Gdby~

CN'

CP

;:,~

.)0~

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 machineoriented 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 tin graphics library for the PC.
e also has disadvantages, however: for one, it was not developed for scientific 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.

B. First Steps with C

226
_

.... f t (

.r

int i;
fore i=4; i<16; i=i+l) printf(lIi=1.d \n",i);
~

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
, ..,...
.
~~ uy Lne
are
LU ue execuLeU; sevP~s). ~ne P
eral such commands must be grouped by braces { ... } and there must be a
semicolon after every command.
This program is compiled with
~very

.. .

....

. .

"" '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

uraH

!llQ

tho ,.

,.

1
'<J

'

. .
'<J

uu Ult::: Ly pt::1::1 UI LUt::

..

fn.. tho

,.

Lilt::

. 1.1

,.

A~AA~" A A A O

tn ha

..

-l

'<J

are commonly used.


Format

Variable type

%d
%ld
%c
%f

int
long
char
float

(ftoatine:-noint renresentation)

,...,

-,=1_ ... +

t.

%If
%s

double
string

II _

rn.
~ lIt::

"

\,;Ua.1 avlJ'I:'~ LuaL

\11 11::1 a

.)
'J

'.&

.&

. ,.

~J AAA~~A

~n 1

\'

..

,.

Y.

uut:: It::t::U. J.L \,;UI

.&

to the RETURN key.


The formatting instructions above can also be used for reading, which is
.
,
. \, "J.
,.
uy LUt::
,.

. , "

wa.... .u. \

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:'

Q(lTllP
.&

.1,'

-l

,1alJ IJII'I:'

i:)all~'I:'

...

..
n

IJIIII'I:'. M.

..

. 1 Tn t.hp t.vnp

. ..
"

T"'"

or 'J

.&

-l

t.hp

-l
auu

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;
a>=b;
a --- ,.

a!=b
a<=b;
a<b;

greater than
greater than or equal to
equa 0
not e ual to
less than or equal to
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' :
case'f' :
case's' :

exit(O);
scanf("y'lf".&:a); break;
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)
pow(x,y)

Logarithm to the base of 10, IOglO(X), x

fmod(x,y)

Remainder of x / y

>0

xy

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)


+;~_ l.~n +~ l.~"

, ;_ +l.~

.11'

1:..

= x 2 e-

z2

/2.

To do so, the func-

(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:
. ..
. ..11'

it,

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 values 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

. 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~

'~/'

dosomething 0 ;

if (a=b)
'T'l...~
.a. ........ r

.44.1.
'T'1
.......... 1
- u. .a. ........
uv uJ P"" u.
o to tne vanaDle a ana tnen tests wnetner tne valUe
not, the function dosomething () is called.

'-'

.1-

,.1

~~~.~

OI

IS

'-'

equal to zero.

11

integer = 3 * rand () / RAND MAX'


All ..........;<:\hlt:>'1 ~nr1

~rt:>

to. ht:> o.f t.unt:> ; .........._

-" . -

C'

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
,.
onp
i~ lo~t. in t.h p
of t.wo
tht:>
Tl
1"

"

_1

_1...] a1

_1

"

..J

'-' L

L1
J..l.l

I-

1-

"....

"V

&

..

_1

1"\

...]

v, .... , u..... u

&

11

()
~

..

-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 command of the for loop, vector [10] =100; ,assigns the value 100 to the memory location after the vector without any warning, and the programmer does
not know what is being overwritten!
main 0
{
,.h~,.. *n~m ...

. : _ ......__
II
,... , "'QUi'"

~_":_+4' (IIt.n.~+

................~..
\

II"/

--

__

~
?
- - - "

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 ;

B. First Steps with C

234

.E

1\.T
l.'QU..U::;.,

QI.'l;::;~

VI.

,_ 1

,I..lVlI

lin."

II

.1

.1lIl..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-

...

~ ~

pr1nl;:I \. \n

..

I.S I.S

\n , msg,nameJ;

l'

The difference between II x II and 'x' :


'T'h~

I"

. .
.A.

lQ

.....

_1.

-~

_1

G.l1U

. .L.,

It. lQ

\,..

\V.

IT'l_
~L.n:::;

l
-A-

..J

Q
~

nf t.h~ t.wn rh~r_

_1- ALLLQI. QL 1I't:'1.

int a=100;
scanf("1.d",a);

scanf mterprets a as the memory address numOer IUU and overWrItes Whatever 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. Prentice 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.
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
passwor, .

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 source code

Pascal source code (sometimes .pas is used instead)

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)

Switches to insert mode (Insert)

Esc

Switches back from insert mode to command mode

Deletes the character at the cursor position

dw

Deletes one word

Jumps to the last line

/ pattern Searches for pattern

240

:x

C. First Steps with Unix

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
wi
.
there.
Networks
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 address has a name associated with it. ft . h sik. uni-wuerzbur . de for example, currently has the address 132.187.40.15. The individual groups of numbers 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
IS

one should use the names whenever possible.


onnectIons to

The command telnet computer can be used to establish a connection to another 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.

C. First Steps with Unix

242

r"'
&- . ,

I"
&&v&&&

'W'

&&&6

.&.

&

co

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..

U1V

TT

a.

V.l

GU.

.I..I.C.lC, IIVU,

a.

, . ,

to

.y

Ul)Cl lldl) IIU

111.11.1-

or hersell; the computer asks tor username and password. Alter a successful
login the following commands can be used, among others:
to

sP.ts thp.

hi

_.:~"I.. ~ 4-

.'

.:I

to

1..
~

Lp.. t.hp n~.t.~. ~.rp

to

'
~

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

, . filpQ

to

&

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
.
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
. .,. .:. .g._z.
~

..:II .

-vrr&&J---~-

TT'1o

,,

.. nn .. n ... ~n ..... ,

\ l;Ullt:l.lL .I.e

.I."~ .I.0'

,.

"

.<j;V .I.tJj 11.1 Ll.lt:

.y /

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
'
"",..;1
" f +'ha
with the command tar xf file. tar the directory is restored.
,-

---_.

~&&~

'-'

~_

V&&~

~_

V&&~

~&&

~,

~&&~

243

C. First Steps with Unix


'T'l...~~

.&. ,u",&&,

~~
&&&

~.&

.... "'.&

4-~

U~

~~

,~ -1:~1

UU/

'"

....&U&'-

&

'*\

~-~
yA

U/& ' "

'U'

,~

..]

A.

uu"'..... '-'

&&'"

'.I.'

rrequently usea program is callea gZ1p' '.lne commana gZ1p I11e compresses 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
, , .
,
~nr1
,.
nn nno
tho
nn ~nnt 'hoY' T .ot
-r
,,

11Cl

.I.'

.I.'

",

'U'

W~

WaUL LU ;jLtLlL aU A

'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

rn1.
.1
.L 1.11., I., UVUC

VUC.

v 10,

.'L

A..LLViCI"

A,
,1..
ogWV "og. '-'II "IIC

-r

ogWV "og

1..
W'V Ilo,V'V "V

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..,

_.IorK

T.l"

.&

T'lo' -,

'-'.

(1(\(\A\

\,&,"''''.&1

Tl..n TT... :.r r\


....u ' V

" ' & & &. . .

..-

C'l
~

'-'J

TTT'
~U'VA&

&&'VJ'

l\T.nn.

'V

~'Gdby~

CN'

CP

;:,~

.)0~

D. First Steps with Xgraphics

,
library of the X-Windows system, and provides simple commands for managing 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 capabilities 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]

E. Program Listings

250
"'.... 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)) .

,
J

end=clock 0 j
printf( II
getchO j

time= Y.f

sec 1I,(end-start)/CLK_TCK);

float average( float* data,int n )


{

float sum=O. :
int i'
ofn'Y'(i =n i <n' i ++)
return sum/nj

R11m:-

ri 1

..........

...

~ ....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!;

r--- . -.. ..... - .-..

_ .... ..:nr11 .rr 1 n..:1

..

. rv Tr,., ;nl ....h;nll/....h;n


c
~-

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,

~c

.~

'C

.~~

E. Program Listings

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,

251

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

_..

r. -" r.

."_-.TT.

~'i.l."

L....

':. _

&.

" t . " , \oJ,

t ...... t

&.~

&.

I
I

A
."

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_

11.

I __

;1. .f_l.":

,,1.1.

t,";..- t . 11. t .fl..


.. , 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}]

:''L.. -t:.

-~

t ... -t -.:

-~

-~

.~ ~

rule = If[$VersionNumber>=3. t

... .....

..... r ....

P1n...Pn; ...... <:-~J;.n

...

N"... 1

I
I I _

rit ....... ., r... 1 ...

ft

11.

I_l.':

11. - Il..

':'1.~' -

t ..--t -. t "r- t . t ..- t .. .. t


~r .. '
~
t"'L"oJt"t
{{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
-.T

.,

r-- -'

......

....- t - .

11. I __
-~

-~

-~

~ ~

...hA1 -~~" .. " "h"'\.1

_n, _v_r ..... " I ...y,u...


I .. 1. ~ ' . ' n
....._,u ................
'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
~ p;lll
~1: n ~P;
T-f:

_.

r~"

~.

____ A

__

=~

_.
r..
t-4=r..,
.. -.. t .. t
{{ataO}t{omtomO}t{phitphiO}t{btbO}}]t

________

1.1 __ ''':

"

~."

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
01511
Pl
~

"

253

E. Program Listings

254
..

'1\ Jr. . . .

..... v

...

..

. ..

..,
-.:-

..

.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
'
..:
__
r...
_~,_rT.;
__
rIn...._:r....
r';.L1:1 _11_fn
"'-.... no n"\.
..
1"'"

L ..... ' ' .......

-~

-~~....

....

r. r.

'r"-

.~

..,

L ... - ....J

.~

J'
....

r,..

'J

Aft A''''

.J-.-~v.vu.v.T.T.J .1. ....

.... , ..

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
oJ
-

..

..

., ,

r,

U.l.D"L.I.-_.D_"I-~''''

0 ' . , ...

J~

."

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"\.
,

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

.&

...~ " l "

...

,...

.................'r,

-~

'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
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
1}
D's la Funct'o ->
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

255

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

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)]}
vosnum = vos I. numvalue
flist=Table[vosnum l.r->100.0*3 s, {s,O,3}]
p 0
0
va ua e
s
1S
, omega,
PlotRange-> 0,1 , Frame -> True,
FrameLabel -> {"omega","Abs[vo]"},
FrameTicks -> {{20000,30000,40000},Automatic} ]
A

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},

257

E. Program Listings

258

D1 ..... +D~-- ..... _~A11

.-

.~

-'::1._ _.. . .r.r


....

i t\t\t\t\
'

-,-

T,..na

Automatic},
FrameLabel ->{lIomega","P/PO"}]

~.'l

_. .

n!:UT1l

. .. .

-...
V.au.a

'

...
l-

III

Print["\n Oscillator Chain \n II]


, -f , 0 , -f*Exp [-I q] },
matl = { { 2f
},
, 2f , -f , 0
{ -f
.(
}.
.
-f
.
2f
-f
0
} }
{ -f*Exp[I q] , 0 , -f , 2f
massmat=DiagonalMatrix[{ml,ml,ml,m2}]
mat2=Inverse[massmat].matl
... r r
- , -J.a.U.&.CL"\.,A"
....
",nopLr..l.geDv 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"},
P

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


:ft; ... ,.lnl'1 ...
*~

__, .. ...1_

~.

_'L

-...

h,>
',;,.."

'h~

&

#define QMAX 400


#define SHIFT 1
mainU
{

int gcd( int , int);


int ie, n, nold, m, p, q, x;
1'1,.... },.1 ...
.&&U

_..1_':

0 ......

...

"l.;onUl
-

.:_ ...

char str [tOO] ;

n;

.-

nl::.;n1t'1

a
'

...

.-

nl::.;
&

.nl::.; ... av

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
r-

259

---, .... ,.
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)
.[

.. y ...... 40- v
;,e,-v

I.

II

... , .. v ....

..

-'/...111

"'1 to.....

...''''1''
.. , ..
.\

........ . ,.

,.

,.,.

.,

..,nAA -..Lv.,;,u.l.r.a..,;,u.l.r.a. -",llAA--..L..LV.';'U.l.r.a. -IoV ..L/,

'-\';'U.l.r.a.

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

.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++ )
.(
...

~ . . . . . . . . y~

C.~I

'l

...

"

(~

..

,,~

...

.\
.,

....

,
psiold = psi; psi = psinev;
...... ,

v.v,

.... ..
r

... ~ ..

,.1~

40-

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... ,

_
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,..

....

'~f~
...... '40-

'"

nVAY

(.,:1,. ... +\,.

..... ,...1\
4O-V_ ..... ,

nold = n;

0;

....
0;

., -:.'
, ... , ... v,

260

E. Program Listings

.,

1..

,I ...

"1_._
-- ---r
': __

/* p-loop */
if (kbhitO) {str[O]=getch();getch();if(str[O]=='e') break;}
l' 1* q-J.oop *1
closegraph();
} /* main */
};

;..,1- lI'''.-I (

.r.

;..,1-

Jll

;..,1- h'\

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]],
-1'\ /.,1 ~, nn.... r,
llr -~'nn.... r(
. . I'll '\1 ~
C'

_rvr,,__
... r".D~

.- ... -.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
.,
...
...
..
r
..
.....,.-1 = T
"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=
...( 1 _ ......,... r r... .; ......... 1.. 1 1 ,
4l,
...
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
.'L

'O~

.'L

E. Program Listings

-, -

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

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
plot2 => Double occupancy in the ground state \n
as a function of U/t \n\n

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->

261

E. Program Listings

262

'[IITT/t- 1I

lIinn'h1 ...

...... v

, ..... 11

...

"

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*

..

r~r ......1

~.

~.

"~

.,

f .... n

,~.

s::: s:::')1.11. f n
"I

.~.

, ~ ,. ')1.1
-" .. ,

g2 = ListPlot[plotlist,
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;
..: ...:
............

....

...
II'" .
, 11\ \ 'V_
... '-0-- .... --, ....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) ;

II. . ...lI_": .... _

(1

"' ..+u;

- _.
_ .. 1

4.

,_.

. .

1 """"vv "",,"vu_1nn i ) .

;"1\,
J' '--J ---"

. /1 _ _ ..: _, ..... / / ___ _1

while(1)
{

X1t=4.*r*x1t*\1.-x1t);
x=xit*maxx;
putpixel(x,y,WHITE);
if(kbhitO)

E. Program Listings

r
_ . ...: 1. (
- - - - - '0'

-'- ( \ \

case ' l' :


case ' h' :
default :
case ' e' :
case ' c' :
case 'p' :

" ,

if (ymaxy-100 y+=1;break;
if(y>1)
y-=1;break;
getch {) ; break;
closegraph 0 ; exit(1);
channel(r);break;
sprintf(str,1I r= Y.lfll,r);

..

'(1 ,v
str)'
w

'h"''''J:lllr

' .... , . ... ,~ ....... .,~


,
-(" \ ,.'} /* 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

.1

r)

......,"" .... ~.= 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
n .. C!h; ...... rrn nn':l n nn':ll.ll.

""-{Thickness[0.002],GrayLevel[.6]},
{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];

-~--

263

264

E. Program Listings

...
0'

...

,W'"

r, .

W'"

..-

W"

,,,..- ... v" L...... ~"'..- ... v" .. ,,] ......

"

....

-"

"

r",

.J;

"'''',

'LV. V-'.J ,

h.y

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....


...1 rv n 1'\.
_. - n "'.... "1.1 .=(...1=Pl",... r... ~r,..
... _. ,. .... ,T .....,. ,

..

--

-'

.;..~--,

AA' -~.... ~"

r, ~ r:'

. ; oIL

.+

'VJJ'

'"

LU.L L1I',.L.J"', V.

oJ, oJvV.J ,
..... "'''',

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],
.;",... _'> T,'"
1
n;"'.....l ....
,

_':J_T ..:
0

_+n,_ _
"'+v

r, . : '1" n,"

.. _ _ _ , .

__

. .

.... ,
..... v

...

...

.-

.... - -. ..- -....

_.... .r.rn 11. .r~" 1 ~ ~


, , , ,
, "',
,

...........

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,

...

n..: __,

-'> T....,....

...

'",-

_.... 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),
",h... l -'>

-.r"D__
.. -

"~_~,,,_

._-___ ,_ , .......
.- ......+1.

",-4'
~

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
,- .- '- .

--

1 .. 1

g[n_,mu_):=Block[{x=Sqrt[mu),l=Length[period[n))},

E. Program Listings
n.... rv=C!.......+r_.. ~(_1\-( .....................Ir...l rr.......
ll\ vl
-..
~.

&-~-

..... , ..., , .... ,

1' .

'::I

_~r

~~

~~'

.. , .....

_1I'L'

265

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
~, r....111\
. ,
- .C!........:r....
&.
&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\

"

..

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");
-

,f\.

O'

'\
~"""'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;*",; ... (')

_.0__ -r.o--.._,

*n;*v\'

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

case

setviewport(10,maxy-20.maxx,maxy,l);
clearviewport();
outtextxy(l,l,str);
se V1ewpor
, ,maxx,maxy,
setv1ewport, ,maxx,maxyclearviewport 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

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, ramerame a e p , energy ,
PlotStyle -> PointSize[O.013]]
hxO:=Table[{x,h[x,.336]},{x,.15,.2,.001}]

PlotStyle -> PointSize[O.013]]

Ice: slerp.c

***** Fractal Lattice *****


#include <graphics.h>
#include <stdlib.h>
main 0
{

"
getch()j setcolor(WHITE)j
while ( !kbhitO)

267

E. Program Listings

268

. .

'\

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}];

. .-

,
~

. --,--,--.1

.T..:J1

.... ,

.'.rr,,.,.

..:Jt'J

.,

..:J":2'\.

.,.

1
J

."1

,\,.&...i> .. ~ ,y.&.u

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..

!1 . L 1

n"n.

TlA'Il..

Viol. '-I.LJ-

'"' ~i:)

/*****

.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

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?


SCanJ: \ ""f:> , S...r J ,

II) ;

.t

else strcpylstr,argvLIJJ;
if ( (fp=fopen (str, "r ll ==NULL)

*****/

E. Program Listings
r,
~ III

,
exit(1)j

...........

OJ

'1:',"

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
continuej
default

.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
*Cln.,.t: (IolClnm) )
;~( l\*;nnnt: <
.,: ......(;.. n.; LW . ; .&-~ , u':; ...,..},.+ r;,.&-= r;, /(41 ... ",-t:)W

4' __ f..: _1>1'1_-4 ..: ..... n

..: __ ,

1-

.- , -

- , -,

neuron[O]=inputj

---_.- -..-..-- ---_.- ..- -...


r..:1_

r..:

_-4

-~

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:_'=
~
" 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]

v:.. . -

r.,: ,r ,rn },. ,.= ,rn .&- },. wr.,: /


.. ru -~ "r-un"
"r
--"
Euler[f_.y_,yO_.{x_.dx_}]:=
NestList[EulerStep[f. y. #. N[dx]]&, N[yO] Round[N[x/dx]]
);",,1

_0-

1'0

.. _. -." -. ,,_r -. --

naml..1l;On = p
tmax = :lUU
dt - 0.1
phiO = Pi/2

~/~

\;OS LqJ

269

E. Program Listings

270
1'\

1'\

I'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

..

....

_ft

....

. YI

.~.
r

r f.

'L

"I' ,

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]},

.
I'... u .......
..

f_
-

'I'
"VA
__

_'\.

.."

1'''''

1"'.
__ ~
V
_ ....

.n..

. ..

'r

_I'\'l..

J_l..":1'\

"1'---' 1'-'"

n..

,A

~ 'Y'

...

J11'\

...1.'l..1

.. --, --.....

.......

..

,.

. . . . U&II...

"' 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 ...


'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"

.a ...

*; ...... 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:

"nw "hAtt Ynlttvnltt Y"iRV V"AV'


"

"

double y[3],f[3],t=O.,eps=1e-08;

E. Program Listings
..........0 ..

10.

..J
-o,;~

-r

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 ,,'~ ....... ,~.&. .......
,~.&. . .,\.,
".1 ._'
..,

.L~

-g'

"

.....

.. .. ..... r" ,

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"
+=+.&.~+

1..

.
.

I?)

l;n",,(vnlt1 vnlt1 vn""u vn""u)'


,
'J

closegraph()j
}

void event (double y [] )


{

svitch (getch(
.(
,. ... e ....

1 .... 1.

~ ............

=... '"

... _.....

....

default:
case I i I :
case 'd ':
case I + I :
case '-' :
case I s I :
case 't ':
c:asl'!

I,.. I

1'\ . '

1'''' ......... "

...
..
,

getch()jbreakj
a=a+.01jprint()jbreakj
a=a-.01jprint()jbreakj
ysc=ysc/2. jprint() jbreakj
ysc=ysc*2.jprint()jbreakj
y[1]=pi/2.jy[2]=O.jprint()jbreakj
poincare=!poincarejprint()jbreakj
'~~ 4? "#11='1")' . "(1~ 4

~(lI'Ji~lI ''''.\ ........, ... +(\

.l.
}

.'..

40 4)

271

E. Program Listings

272

....... .;~ ~ __.; ....

(~

.......l.' . . .

~ .......

l.'_ .....
J

.......l., ........ .&\


-,

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
,.1 ......_.; ..
n .

...

.m~Yv
"

1)

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"


".+,-.toggle,clear,arbitrary");
setcolor(LIGHTGREEN);
rectangle (9 9 ximage+11 vimage+11l'
II

.l~,..

IIIH I

....

,.

...
...="'1 oF II ....
if(poincare==l) sprintf(lstring[strlen(string)]," - Poincare");
outtextxy(320,yimage+40,string);
setviewport(10,10,ximage+l0,yimage+l0,1);
.. p<_,; ... +oF(

.r

II .. ="'1 oF
..
...

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
"" . .....
.., .. "........ , ............,,,,,,
.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,
"'

...... ,. ,... .,

--

... a.i:>'C

.- 1\

~.

.....1'.10 .loLl" \

l-t \

. .". . ,

_...

""

.......... v " .. ,

'C , U'C , U,A,J ,

default:
case '+J :
case J_ J .
case 's J :

getch();break;
e=e+de;print(e,de,dx);break;
e=e-de;print(e,de,dx);break;
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;
............. J..:I J . . :1 ....=..:1.... /" ........; ... + ( ..... . :I.. . . :I....'.'
..
'r
_ ' ....l.. .. 1
1..1.
,
,"
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;
}
(I'In"hl ...
.
,- .. - ... ,
clearviewport();

void
.[

_\,~ _ _ +_r'll\nl

A I'In"hl ... dA I'In"hl ... dy)

273

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

, ....

..

~,.

... ...... : - :
\-1'-

... ,

1.:1.

~ ....t'~

:""~"

......._"

--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 ....... ,
'C

.. -... ,,-- .... -..

" I
.r..:ll--... ......
... --

_, .... 02r.: .1n' ._/T~r ..' .... r ..'


c
"--'

1..:11...

"'I

'
~.

,...,...,...

-r~ r. '
~ ... L"~W'C--, UUI. ...... .u-...

_.._-...,. ,.

nnl\
----,

,_

~.

.:

"
........... .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];

- _-_.
...

D1,...+r....' rvl
-~

.,.,
...

rv
.~.

_,

"'V"~"I"''G

._in . n .
1

1. D1

...

.n

_~A11

_- _--

.. _..r,... ,...,...".,

LV. VUI..1

... .............
...

..._.

A ..... _ _ ,

.., ._

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.

.. . -

- - "':

-'> Th;

r,-

_~

_ 7'"'" "

rol

.. .. .

- _.

',.

',. r_1

.1\
..... f.. .. 1
... ,
AxesLabel -> {IIt". "X". "U"}]

_ _ 'W . . .
n.'

--.,

...

__ ....

11.1.

1\

~"-

, _ ...oJ,

plot5:=ContourPlot[-u2[x.t].{t.-l.l}.{x.-10.10}.
PlotPoints->100.
ContourShading->False.
PlotRange -> All.
ContourSmoothing -> 4.
-

..

_'> J'"+" " v ll'\.

h ...l

....

........_,

1"1

...

_ .....

1:".. ' - -

rn ..

......

~,

....

1"

..

n ~ LO"
... .... n- ......A .......
"'oJ ..
I'

....

v.~~

I'

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


.~

275

276

E. Program Listings
...l

A ~ T.'I'YIlo_...l

co

,'I_

--11-<;;>

&'

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}]
.
..,
. il;J
UIl~"v'C ... "v.l.~ napL\tt/O)q.l.'l;Ltt.ttJJf,
.
Pl.o't 1: =;:mow Lurapn1CS~lJ Lu'o1n'ti)1Ze LV. VVIiJ ,
Map[Point,unitvectors]}],
ViewPoint -) {2,3,2}]

'-

........

= .f276. 164. 442.l/m (* vector closest to .f0 0 Ol *)


hi h? h~ Rn~n
. llnH~ rAll *)
{-113.
,
172., 7.}/m
=
= {173., 113., -172.}/m
= {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]
vO
(*
b1
b2
b3

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
ts=y ~x+C)j c=Uj)"
{s=y-(x+c)-18j c=1j}
else
x=yj y=Zj Z=Sj n=69069*n+1013904243j
return (z+n);
1t~y)X+C)

E. Program Listings
l

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
}

_. -~ .,

'r.'.

..... 1

... '"
. ,:11
_.._--

A
--00-

'"'

/***** Fractal Aggregates

*****/

#include <graphics.h>
#l.nclude <stdll.b.h>
#include <math.h>
#define lmax 220
#define rs (rmax+3.)

......

.....

--'"

....~ r

--'.

_1.":"

ro

,-- .

(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
.1,.,.... tWHI -..:

Diffusion Limited Aggregation");

..

,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[lmax/2] [lmax/2] =1;

xf Ll.J LjJ =0;

277

E. Program Listings

278

.";~
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
default

closegraph();exit(1);
getchO ; break;

}/* while */

~/. _ .. oi ...
~

....

yu .......

"

J ......l ' \ 1

switch(random(4
{

case
case
case
case

0:
1:
2:
3:

rx+=1;break;
rx+=-1jbreak;
ry+=1;breakj
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,
.1,..... (,.,..1,....... fl,
,1,..... (, .1'\

_..:

.,

II') ..
fA
, . _ - '---'" -

_J

.f_. __ _':11'\\ II') I')~'~


'--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
r

.L'

.oJ

'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)

,; , .

... 1",...

, 3' .

"

'

l.

5.3 Percolation: perc.c and percgr.c


percgr . c is aVaiIaOle on

I.....

Percolation

'include
'include
'include
'include

\jU- tU

amy.

J IVI

<graphics.h>
<conio.h>
<stdlib.h>
<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 (;

&'

&'

&'

closegraph 0 ;
}

..

T"lIo

..

tJ. ":I: C UJ.y J..I.J.CJ.

,... ..

J.

.
&

Available on CD-ROM only.

'J

.\;

WHIT":

279

280
Fi.Fi

E. Program Listings

..... . . ,.
....
....
.... -...
1***** Ising Ferromagnet: Text Mode *****1
T

#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 ....... ""

"' .

.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)

for(x=l;x<L+l;x++) for(y=l;y<L+l;y++)
{
~

,~p

,~p

~ ~

e-s LXJ LyJ ... \ 5 LX-.LJ LyJ ~5 LX~.LJ LyJ ~5 LXJ


1Il e<u II randlj<DILe/:lJ )
i.

s [x] [y] =-s [x] [y] ;

Ly-.LJ

~5

,~

LXJ Ly . .LJ ) ,

E. Program Listings
~nn

.-- .. , "'";::';~,~
_", ... 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++)
{

- -r.".1'-

a rn1
-

=a rr
_. 1 r.".1
_._-

*/
*/

- ..- -.. ...... - .. -....-. ,


~rT

~-

.~,r_,_~r~,r_,.

r."rn'

LAJ LVJ

-g

r~_,r,.,
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 ....

;.:!

""

" 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

281

E. Program Listings

282

, . 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

... .,
& ....

AccuracyGoal 86
Aggregate 166,167
- fractal 170
17
Aliasin~
Alternating current 52
Alternating voltage 52
Amplitude equation 140,143

Apply
A

"

-J

-su,

.......
,&.

..1

... ,

....

... ,

...",
U

?n~

,
,,,,,,

0'7 11lA

"

~~

1')<)
~

... ~u

Band 65 78
- chaotic 90127
Ell'

,~a, ~~.:>, ~~o

.tnIurcatlon POInt lS4


Bloch theorem 65
Block 4,86,218
Boltzmann constant 39 190
Boltzmann factor 196 202 204

,~

1111

176

~~~

0",

0"7

u ... ,uu,u
,

n1

nn

o~,ou

char 5,225
Charge distribution 30
Charge, total 31
Chirikov map 94
X'" distribution 24,26
ChiSquareDistribution
X2 test 23
.,

26

R? ?lR

('0,,; ...:,, __

'11
r;:

.1.

Cluster 165,171,172,175,177,180
Coexistence 40
Compilation 6
Lioncentratlon, CritICal n:t:
Confidence interval 24, 26
Confidence level 29
Contour 27,32
r.j

Basin of attraction 123


Benard experiment 129
Bessel function 21

&

0'

'Pln+

r"1.

Q ~? ?14

('O,._ .. ~._-

DeSSe.LJ

1~~~.

-~

- strange 123
Automatic 105,213
Average 138
- statistical l~a,l~~
- thermal 199
- weighted 20

T'"

rl1..

r.hnn

Ronfl

.1

4
Approximation 48, 138
ArcSin 8,213
Array, two-dimensional 168
Arrhenius' law 198,202
AspectRatio 105,213
Assignment 54
.. +n;

119

. .~ & U

.10

&

,,,,,, ,.1 ... '~r!:


I I , .LV"", .L-S I , .LVU

......

case 112
CDF 26
ceil 133

~~

"

.'

LJ

- periodic 60,73,195
break 112,229
Bulirsch-Stoer method

I::.Il

T'"

OJ

")'1

"'-

Control parameter 129,199


Convection cell 127
Convergence 109
LionvolutlOn 14,~1
Coordinate representation 47,145
Correlation 159
- length 175,193,197

.. .

~.
~~

140
4R 71 7~

284

Index

rI.

rI
LJ~~

-Critical exponent see Exponent,


critical
Critical phenomenon 172
Critical slowin~ down 199
Crystal, aperiodic 19
Curl 37
Current density 146, 166
UVU,

~,J

-u

.....

oJ

T'""

- ...............

'''-

"1"7

V"

1'1
-_,

10'1

10n

....& n.~
~.

~,

-...

.......
.,..,

orr

'l1

r-.

.1..,
_1...1
~

-.......

~v~v~

..

..

-4l __~

.......,
'lO

'7~

'11A

'1'1'l

.v, ... .L.., .........

rr

1 ....

.L'2:U

~'l

.1..

-----..

~ '1'1l:::
v,
__ '"
1"70

Double-well potential

~o

1:'..... 1 ..... + ...

......

...

Fast Fourier Transform (FFT)

')')1

..

~O"',~OoJ,~ou

Expansion, symbolic 11
Explosion criterion 134
Exponent, critical 174, 181, 182, 193,
199
Expression, logical 54

Dipole moment 30,32


Distribution
- initial 146
- - symmetrized 148
- stationary 185
Do 4,86,138,141,219
Domain wall 195,198
nn+

..,..,.....................

An
.""
Equations, system of 52,56
- linear 47,59
Equilibrium, thermal 190-192, 195,
198,202,203
Error, local 118
Euler method 116, 119, 120
Euler step 118,148

, ---, l~A
--, 1'71 , 17A , 1'7~
.

nno

...u., """"u

I'n .."'..

11 ~

....... .Lv"',.Lv",

. .-

101"7

Energy 190,202
- eigenvalue 50,131
- landscape 208
- level 42,51,77,134
Equation
- implicit 149
- of motion 60, 118, 120

_-v

-~

... ~

.cJllU- lIV-t:llU

1(\') 1')'1

.1

~~,

'l~

...."

T'"'

- partial 136,144,148
Diffusion 164,195,198
- equation 164
- - radially symmetric 166
- limited aggregation 164
Dimension
- embedding 102
..

~'7 ~fI

-~,~.,

,-I, iJ.l,
...
U.l

A' - - - . .

...
...........

.. ,.., ............. ,..

11'"
...... U

--, ~r::

~~,

1:'"..:_... ..:_u

117 ~o

,.

-~,

1..11::

- - generalized 60
- problem 66
Eigenvalues 49,62,76,221
Ei~envector 47,59,61,66,76
Elliptic integral 7
EllipticE 35
EllipticF 8

Determinant 72
Deterministic system 113
Deviation, quadratic 24
Devil's staircase 99
DiagonalMatrix 49,61,220
Difference equation 137,149
Differential
equation 82,203
,.
.~-

1<)1

~"A

~OiJ,~~~,~~~

_ ..... 1.-

~-

. .,. --...

,.

-.

A'7_ .AfI r::fI ~1

'.

'70

v, .v, ....,... , .....,

lA'l

-.

....,
'7C

I, ~u, "'~~

..

~~

Eigenmode 61,63,139
Eigenstate 47,65,77,131,145
Eigensystem 76,221

Data
- nOISY 22
- smoothed 21
default 112,229
#define 5,125,227
Degeneracy 78
Derivative ,39,84
......

~~AV,J

Dynamic
- continuous 94
- symbolic 84,90,92

QQ

.~

.. 1

--, 1')7

r'l.....1""

..."''''Vl' ., ...
,
...... -.-

11 '1

11 n

"".

51,121,135

.L.L""

Fibonacci number

19

~~

15

Index

- .

.... ;"'1~

')0

.~.~

- magnetic 34,63
Filter 56
FindMinimum 25
FindRoot 41,84-86,98,218,221
Finite size scaling 175, 178, 181, 193,

199
95
"P

'[;I,'

.1

. .

u __

'

on 0,.,

rt.

PV&&&U

u~,u.

" " ........ u __

.J

D.'

... &A,",U

?"l. ?h
00 no')

~.~

,. ...

VI

98

Gradient 30,36
Graphics 31,105
Graphics object 31, 105, 158
Graphics3D 159
Grassberger, P. 123
Ground state 76,78,94,99,131

.....

~J

11 n

... ..,'"', ...... v

rt

vv

Ji'lr

1 nO

"

'In

First

.".
.
- .., ,., _.Golden ratio
("1

~~

~_~

~~,~-

hO 70 '>Wl
,

1 "70

~ A

1
..-

1 Oil

...,,_~v

1 ......

... V"Z, . . . . .

Flatten 62,74,105
float 5,225
Flory, P.J. 182
fl'luctuatlOn 175,192,195,198,199
Flux
- area-preservmg 94
- magnetic 64

- normalized 145
Harper equation 64,66,70
Hermite polynomial 48
Histogram 86

Ji'111'V

J.Ti+ ..

RLl
..

.........
...

IT" L.,.&

-~-

TT'-:'

n1 n

-.:,~

...

.,

"LI:!

T'\

T'\

fifi

- 52,55,60,152,210
~

, -v, _.. . _.. ,

"7 11l 1') 1')1

R~

-...,

Gam 42,44
Game of chance 46
Game theory 42

~~j;l

n.

gcc

~Q

.. ..

6,240

,.,n
v

VV

Hoshen, J. 177
Hubbard, J. 71
Hyperplane 108,109

If 41,76,218,219
Impedance, complex 52
Implicit method 144
T

.. "

..

fi l?fi ??7
l'

1 '>.11

-_ .

11')..4
"-oJ

14R

...,

... vv

ou,",t'

1'>1:;.
1 ')')

.... ,
nteractlOn
- attractive 183
- magnetic 172
InteractIOn potential !J;j
Interference pattern 146,153
Interpolation 141
Inverse 61,221

Function
- Boolean 108
- nonlinear 93

~'l

1nn
... .,.,

~~

1 '>0

T.'I

&:.').,

Initial condition 61,83,121,165


Initial state see state, initial
Initial value 116,132
Imtlal-value problem 104
Initialization 138
int 5,225
Integrate 9,11,37,220

- inverse 13,55
Fractal 102,105,123,173
ttrequency
- angular 52
- fundamental 146
- incommensurate 97
,"

110 11'>

fH ... ,..1 111'1 ...

R hLl

(;101'10(;1

T.'I

_.n

;.

oJ

for 5,33,179,196,226,229
Force
- gravitational 120
- perIodic l~~
Forward-two-point formula 137
Four-cycle 83,90
Fourier 8, 15

""-

149

110')

'r--

48,51,71,73,75,119,

Hamiltonian

24

'>0 1~'l

.1

".

'lIer

15" 21
1

u",l11 0

Ising ferromagnet

~I:;.

1?~

192,197

285

286

Index

Isotropy 165
Iteration 84
- inverse 85,90,150

KAM orbit 98 100


Kernel 20
Keyboard buffer 206
Kirchhoff's law 52
Koch curve 106

Lattice
- cubic 164
- gas
- square 172
- triangular 172
- vector, primitive 159
- vibration 59, 62
- rule

Minimax theorem 44
Minimum, absolute 202
Mod 96,158
o e unc ion
o u e
Modulo function 95, 158, 161, 187, 227
Molecular dynamics 118
Momentum 0 erator 64
Monomer 102
204
Monte Carlo step 210
Multiparticle state 71, 74, 190

107

Leath, P.L. 177


Length 4,76,216
Line
Line integral 36
LinearProgramming 42,45
Liouville's theorem 94
Liquid 39

83,91

Network
- electrical 52
- linear 54

Nonlinearity 7
NonlinearRegress
Normal mode 60

25,217

,
132
185,191

Index

- algebra 74
- unitary 149
Optimization
- com inatorial 203
- continuous 201
- discrete 201
- linear 42,44,201

287

190, 198
Phase velocity 152
Phonon 59,62
Pixel 86,103,134
Plot 8, 141, 213
Plot3D 32,213
PlotRange 8

- superstable 84,85,90
Order
- magnetic 172
r er parameter
Oscillation 138
- damped 126
- longitudinal 59

Oscillatory circuit

Poincare section 82,94, 123, 126


Point 159
Pointer 5, 230, 233
Polygon 10
Polymer configuration 183
Polymer dynamics 183
Polymer molecule 102,182,186

52

54,58
27
23,28
37,214

42,43,46
19,210

Power spectrum 19
Precision 91
Predictor-corrector method

119

printf
,
Probability 43, 145
- density 164

122

172,175

74,216
49,83

Phase space

9, 11, 120, 122

Quantum Monte Carlo method

78

288

Index

5,103,158,168,177,206,230
RAND~AX 5,168,170,230
Random 4,158,159,214
random 96
Random motion 164
Random number 4,21,46,113,157,
205

y
,
,
- time-dependent 144
Schroeder, M. 106
Sech 138
Self-avoidin walk SAW
Self-intersection 184
Self-similarity 104
Sequence, periodic 158

- - subtract-with-borrow 160
- normally distributed 29
- uniformly distributed 162, 195
Random vector 102
Random walk 102, 103, 164, 182, 183,
189
Rectangular voltage 58

Series representation 145


Shooting method 132,135
Show 31,213,216
ShowPro ress 26
Sierpinski gasket 104
Sign change 67,68
Simplify 38,220

Relaxation time 195


Renormalization group theory
193
Re lacePart 75
Reptation 184-186
Resonance 54,56,57
- curve 56

Single-particle state 71
Site percolation 176
Size, average 165, 173
Soliton 136
Solution
- analytic 41
- numerical 41,47,51, 71,115, 141

rand

174,

,
Richardson extrapolation
Rosenblatt, F. 109
Rosenblatt rule 110
RotateLeft 21,138,141
RotateRight 141
Round 119
Round trip 200

163

118

Spectrum 63
Spin configuration 191
Spin correlation 80
Spin lass 202
Sqrt 9,49,212
Stability 143
- condition 143

State 94
- commensurate 95,97
- incommensurate 98, 99
- initial 83, 150
- quasiperiodic 98
- stable 93
- stationary 47, 145, 191

182

Index

,
- stochastic 44
Stroboscopic illumination 123
struct 103,178,186,205
Sturm se uence 67
Subharmonic 83
Sum 32,75
Supercomputer 191

Two-cycle 83
Two-person zero-sum game 43, 46
Two-phase line 39,40
Two- hase mixture 40
Two-soliton solution 142
Type declaration 5, 103, 225
typedef 161,186,205

,
switch 112,169,228
Symmetry 66,68,69,74,78,131,133,
145,146,193
- reaking, spontaneous 19
Synapse 106
Synaptic plasticity 108
Synaptic strength 108

Taylor expansion
Temperature
- critical 39, 41
- norm lze
Tensor 4,30
TeXForm 12,77
Thickness 31

unsigned long int

,
161

Vacuum 72
van er
s equatIon
van der Waals gas 38
Variance 24,162,200
Vector 4,30,229

116, 132, 139, 153

Time derivative 140


Time evolution 149, 153
- operator 148
- quantum-mec amc
Time scale 123,198
- characteristic 152
Time series 110

- Gaussian

Transition probability 185, 191, 194,


196,202
Translation 60
- opera or
- t eorem
Traveling salesman 200

Winding number 95,97,99


- rational 97
Witten, T.A. 163
or 1ng reC1S10n

155
183
107,112

Zaman, A.

160

289

~'Gdby~

CN'

CP

;:,~

.)0~

~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,

.u, .1"

_1.
OJ

OJ

manufacturers, etc. - to commit


themselves to using materials and
,
,
,

r-

"

Ulal uu llU l

.1"

the environment. The paper in this


book is made from low- or no-chlorine
pulp and IS aCId tree, In contormance
, , r
. ,
. .
"

WIUI

IIII~J

I'"

I, Jill ....

~I

permanency.

-~

~4~
~

Springer

.U"

IUI.1"

w. Kinzel/G. Reents

Ph~sics
bq
C0m
PUte r

Computational Physics has undergone rapid development in recent


years and is being integrated into
physics education as a standard part. This course,
intended for upper-division undergraduate or graduate 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, MonteCarlo simulations, percolation, polymers, combinatorial 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

Das könnte Ihnen auch gefallen