Physics by Computer Programming Physical Problems Using Mathematica® and C Springer 1998 PDF
Physics by Computer Programming Physical Problems Using Mathematica® and C Springer 1998 PDF
Reents
Ie
b~
ut
Programming Physical Problems
Using Mathematica and C
W
..
Springer
Using Mathematica and C
The cover picture shows a space-time diagram of the probability of presence of a quan-
tum particle in a square-well potential.
This American edition has been revised bv the authors. The book was oriQ:inallv oublished
in German: W. Kinzel, G. Reents: Physik per Computer, Spektrum Akademischer Verlag,
Heidelberg 1996
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
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
? .
1""".1 OJ.'-'O r
" ... ,
~ ~
oVJ.J.J.'-' v...
." ..1. ~ ,~ ~~ ~I. ~
'H J.J.J.'-'J.J. ....... '-' .... u UJ.J.'-'
..1
uo '-'~o'-' v ...
~ ,
..1 ~
u.J.J.~ UJ. J.~O
. .1.1.
1
Con"",..; ..1 th:lnk~ uo to t.hp.
. .... V,
11
. ,.
..
.... "..,. .. . ..
........
.1.
T
.:L
10"" I.
.
r. . . .
...
.
~~
""'.~
'C .... . C.... ~"'9'
1\ If.
'C
, J.'.La... IIJ.J.J. UJ.J.~
on Unix, and Ursula Eitelwein typed the manuscript of this book in UTEX.
Finally we would like to thank Martin Clajus for valuable suggestions in the
. .. .1.1. ., .. . T':' ...... .
v .. ""
.... IIJ.J... O J.J.""V ....
TTT.
'0
TrT
' . J~ .
'" 07
'07
'V.:... _~l
..... U 'UN,",U
or .. . .................................................. ..
~
1. Functions In Mathematica
. ............................... 3
1 1 . ..,. . ~- 'I
. .............................. A
,. ,.
4
L~
.... .-n1
~lle
.... T
1...
T"Io
.I.
1 1
............................... u
1.3 Fourier Transformations ................................. 13
1.4 Smoothing of Data ..................................... 20
4 ,.
.. ...... .......................................... nn
.... T
LtJ .1' .I'lL ~tJ
A.
-. .:neps wun
.rlrs't
~ . . --a.,;nemanca
..
lY.l . . . . . . . . . . . . . . . . . . . . .t;ll
gram which is supposed to solve the problems from the first part is described.
Only the essential commands are explained so that the readers can try to com-
x
codes are available on the enclosed CD-ROM. In the results part, some re-
sults of the computer calculations are illustrated, for the most part in the
for each problem. The choice of these citations is, of course, subjective and
no claim of completeness is made. At the end of every section, there is an
exerCIse.
...
nil
.
II.l.le
- .
.................. u .lUC.l
_ . ,.
.lCVC.l U.l p.l
..
.
......
I'
...... ...... , CL.l.l'y
o. .
processes small packets ot on-ott data t bits) step by step. ~very packet gives
instructions to electronic switches that cause the results of elementary math-
ematical operations to be written to memory and new data to be read. This
level ot processIng elementary InstructIOns step oy step, nowever, IS narmy
suited to the formulation of more involved problems by humans.
This is why complex algorithms should be structured. Correspondingly,
high-level programming languages consist of functions or modules. In order to
keen a nrOQTam comnrehensible one should use modules that are orQ"anized
~-~~
.... "'...... ...... +~ .c~~ A ~ ~ _ 1~ ~ _~~..:J
u'" ................ A..., ................., .... 0"''''..... .....
~4-9.1~ 99.:11
...... "'UJ""'" ." .........................
C
~ 14-:~1~
..
..
levels of modules; this has the advantage of simplifying the modification of
such programs by making it more likely that only individual functions will
l. n
...... 4-,..
....""..." J.,."
u..............
_L -l
. .
. . .large . .
.- .
lV1 a~nemanca
. ....... UI
IS a programmIng language
. lug a
functions that are easily called, however, since most parameters have default
values and do not necessarily have to be specified. Indeed, every command in
..... ,., , ,.
t;au
. . ,
U~ .l COCL.l u c u
. CL1:l CL
"
LUCLL I:)
. .. .y CLUU
is relevant for all subsequent and sometimes even for previous commands.
In this sense, Mathematica is located right at the top of the hierarchy of
programming languages.
By comparison, C, Fortran, Pascal, and Basic, although they, too, are
,-' .'- 1 rr
'~~1 and . '- . .1 1' .
...... ..
I ,~
...... ...... ......
~ -~~
...... ...... ...... ..
(after all, Mathematica is written in C), require much more effort than Math-
ematica in order to, say, generate a graph of a Bessel function in the complex
..nlane. ,
'T'1-.:~ ~1-.~~4-~
............, C ....,
:~. -l -l 4-~
u'"
4-1-. ~ -l 4-~ 4-1-.~ .. ~~ ~~
u........ .. ................... u'" u........ ........... "'..
"Af J.J..~
....~ ...,Vl""",
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
In this case we use functions that take advantage of the structure of Mathe-
matica. The argument data is entered as a list of numbers. Apply replaces the
Note that average appears three times: as a local variable and as the
name of two functions, one of which has two arguments, the other just one.
case.
The reader will find an introduction to Mathematica in Appendix A; nev-
ertheless, we want to point out some features of this language here: the un-
derscore character in the argument data_ indicates that it can be replaced
: = reevaluates the right-hand side each time the function is called, whereas
= evaluates it only once. For example, r : - Random [] will result in a new
1.1 Function versus Procedure 5
start=clock 0 ;
printf(" average = y'f\n",average(dataset,LIMIT;
end=clock 0 ;
double *data means that data contains the address of a variable of type
double. Warning: dataset [1000000] is some undefined entity; referencing
it will not cause the computer to report an error but will usually produce
comp ete y mcom re enSl e resu ts.
Unfortunately, a comma, semicolon, and various kinds of parentheses have
completely different meanings in C and Mathematica. But why should life be
easy for computer users?
a value close to 0.5 after about ten seconds. By comparison, the version
6 1. Functions in M athematica
Literature
, ,
Wolfram S. (1996) The Mathematica Book, 3rd ed. Wolfram Media, Cham-
paign, IL, and Cambridge University Press, Cambridge
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
t 1.3
cos <P - cos <Po
Obviously, the period T is four times the time the pendulum needs to reach
its maximum angle <Po:
Since the integrand of (1.3) diverges as <p' -+ <Po, it makes sense to use the
substitution
1.
<Po
which results in the following integral:
t
1 - sin 2 (<Po /2) sin2 "p'
T=4 1.7
we look at the phase-space diagram ep versus <P for various energies E. The
generation of higher harmonics with increasing nonlinearity is visualized by a
Algorithm
by the commands
8 1. Functions in M athematica
and
EIIipticF[psi. k-2]
where we have set Jf79 = 1. The command Plot draws the period as a
function of CPo:
-)
phinorm[x_.phiO_]:=
2 ArcSin[Sin[phiO/2] sinepsi[x T[phiO]. phiO]]/phiO
flist = TabIe[phinorm[x.phiO[i]].{i.5}]
We can now draw this list using Plot, after first applyin the command
If, in (1.1), the energy E is kept constant, one obtains curves in the (<i;, cp)
plane, the so-called phase space. Plotting these curves is surprisingly simple
in II lL
.- r~l1infJ" r
hv "', 01: for t.hp .
.... R(ln
, .
II)) 1'hp
.
,.,
'"'v.u. ... vu..Li:> .... 1.J;o.L,
r ..... ... ....
J;o~, ,
~
"".. "1
~J ~a.u
1-
tJv UOVU
.J
lIV
1-
ua.vv 'IJ
0
.1
.L-
.-'1 .
"'V.L
various values of E.
Finally, a remark concerning the series expansion of T(cpo). The new ver-
. (q {\\ . II lL _11"_ ~,,_ _ l' "P_ l__ _.f (1 7\ hn
"'.LV.L.L \ V.V J V.L "'~.L .... ~'-J -..- ....~. \~~
I "'J.
usmg tne commana ::ier1eS, wnereas Olaer versIOns Wlll OUtpUt omy IOrmal
derivatives of of EllipticK.
A possible way to handle this problem is to start with the integral (1.6)
for 'ljJ = 7r /2. The integrand is
p p .~ .~
:r - .11 ;:>qrl;; L.1 - m ;:>~n LpS~J ~J
with m = sin 2 (cpo/2). f can be expanded in terms ofm, e.g., up to 10th order
in m 1 ()
,
- = Series
fT rf {m 0 lO}l
Then, every single term can be integrated over 'ljJ by using Integrate. Finally,
the value sin 2 (cpo/2) is substituted back for mvia /. m -> Sin [phiO/2] "'2.
Results
.
Wp h::t.vp
1- . ~,,-
_1 t.hp
.. '
rr of t.hp
. ,,- .J ~1
l' .1 {I)n
T.'~
. ~
1
...
_1
... .1-
i~::t.
.1-
of t.hp
.J fJ'1
.J.lIJ, VJ.J. lIJ.J.V VI. lIUv ..- .I: J.5Ul.V .............. ~ .... 1IJ.J.'-' ..- .L
."'.....
IVI I
8Pi
6Pi J
T /
~
4Pi
2Pi
()
0 Pi/4 Pi/2 3Pil4 Pi
~lg. Tne penOd 1. as a tunc-
L 1.
phiO tion of the amplitude <po
10 1. Functions in Mathematica
0.5
s s"
because of the periodicity ep(t) = ep(t + T), the frequencies W s are integer
multiples of 21f IT. The discrete Fourier transformation available in Mathe-
(s-1)(r-l)
21fl
6
....,
.......
~4
......
'"
< 2
0
2 4 6 8 10 12 14
1.2 The Nonlinear Pendulum 11
such phase-space curves for different energies E. For small CPo, one obtains
a circle that becomes deformed as the energy increases. For E > m 9 l, the
2 2 2
> ------------------ + ------------------- + -------------------- +
8192 32768 524288
P 1 P 1
184041 Pi Sin[----] 41409225 Pi Sin[----]
2 2
> --------------------- + ----------------------- +
phiO 18 phiO 20
147744025 Pi Sin[----] 2133423721 Pi Sin[----]
2 2
-3
-Pi -Pi/2 o Pil2 Pi
phi
12 1. Functions in Mathematica
> O[Sin[----] ]
2
2 32 128 8192
39691rsin lO !EQ.
2
533611rsin12 !EQ.
2
1840411rsin14 !EQ.
2
+ ----3-2-76-8---=-+ 524288 + 2097152
414092251rsin 16 ~ 1477440251rsin18 ~
+ ----5-3-68-7-0-91-2----'''- + 2147483648
21 11
+
ExerCIses
Start: bo = COSct,
Iteration: bi+l = Vaibi ,
Sto :
- 2an '
xamp es
from Classical Mechanics to Fractals. TELOS, Santa Clara, CA
1.3 Fourier Transformations 13
,
Zimmerman R.L., Olness F.I., Wolpert D. (1995) Mathematica for Physics.
Addison-Wesley, Reading, MA
his or her disposal: the decomposition of the signal into a sum of harmonic
oscillations. This tool, which has been thoroughly investigated mathemati-
most any signal, even a discontinuous one, can be represented as the limit of
a sum of continuous oscillations. An important application of Fourier trans-
unc Ion III erms 0 simp e OSCI a Ions pays a Ig ro e no on y III P ySICS,
but also in image processing, signal transmission, electronics, and many other
areas.
Frequently, data are only available at discrete points in time or space.
In this case the numerical al orithms for the Fourier transformation are
particularly fast. Because of this advantage, we want to investigate the Fourier
transformation of discrete data here. In the following sections we will use it to
smooth data to calculate electrical circuits and to anal ze lattice vibrations.
Mathematics
(1.8)
N
_ 1 '" b . (r - 1) (8 - 1)
ar - -- L..J s exp - 21I"1-'-----'----'---~ (1.9)
s=1
Thus, the signal {ai, ... , aN } has been decomposed into a sum of oscillations
bs
c r =--
s- s- s s
of an amplitude and a phase. Both (1.8) and (1.9) can be extended to all
14 1. Functions in Mathematica
perlo
(1.11)
symmetry:
1 ~ . (r - 1) (-8 + 2 - 1)
= - - LJ a r exp 27fl N
(1.12)
Let the sequences {h s }, {gs}, and {fs} be the corresponding Fourier trans-
forms. Combining the Fourier expansions
. (m - 1) (j - 1)
N
1 N_ . (n - 1) (r - j)
Ir+l-j = N Lin exp - 27fl....:.....---:.....-'------.;....;...
N
1.3 Fourier Transformations 15
I 1 '\ 3
h. - I --.::..- \ '\' n. .I.
L...J
\yN} r,j,m,n "
. (r - 1) (s - 1) - (m - 1) (j - 1) - (n - 1) (r - j)
xexp 2~1 AT
.1.1'
.
The sums over rand j can be evaluated
~
L.J
Avn
-r
(?'7I"l
\
lq.) - 1\T Ji
. .,,""
. ... , lo t=. '71.
t:....:l
NJ
Thus, after the transformation, the convolution turns into a simple product.
The inverse transformation then yields the convoluted function
hr
l:!...
) fl.'l Is exp 2~i
(".
'
l'-, , (r: n
"
. (1.15)
~
lV
s=l
In the next section, we will use the convolution to smooth experimental data.
Algorithm
It may be interesting anyway to look into the Fast Fourier 'I'ransform (FFT)
algorithm. The most straightforward way of calculating all series elements bs
accoraing to ~ l.lS J amounts to mUltlplymg a matrIX OJ tne IOrm
, , .
IN ~ ~,
N log N. To this end, the sum (1.8) is split up into two partial sums with
odd and even indices r:
16 1. Functions in Mathematica
t=l t=l
+exp
1
V2
Here, b~(N/2) and b:(N/2) are the Fourier transforms of the coefficients
F(N)=2F(~)+kN. (1.17)
Application
n=-oo
(1.21)
00
bs
v'N -
_ [.
exp 1 71"
(N - 2) (s - 1)]
N L
k=-oo
fI-s+kN. (1.22)
00
L fI-s+kN (1.23)
k=-oo
\
0.1
\ \/ \ ~ --
0'-- .......... v --...VV~
....... ........_ _--'-----'
5 10 15 20 25 30
0.8
0.75
0.6
0.5
0.25 0.4
0 0.2
-0.25 0 .... AA IAAA
V"
-0.5
.
- -~ v ~ .. ..
- -~ v ~ ..
. ro.f 4-l. .... "
AO _._. - J~~ ._-- ~ \ ~J-' - - ~ \ 0;"00' -- ---
inverse Fourier transformation to continuous t values
. ..
part aoove, we nave snown tnat tne sum can oe taKen over any InterVal or
. .
length N. We take advantage of this freedom to choose an interval that is
symmetric to the origin and use only the lowest frequencies:
N/2
~ t. \ 1 ~ I. '" ~r - 1) ~S - 1)
J \"rj
V'" s=-N/2+1
1 N/2
. (r - 1) (s - 1)
= r:-; ~ bs exp - 21rI 1\1
.l.Y
V lV s-I
1 ~ b [ 2 . (r - 1) (Sf - N /2 - 1)]
+ ..;N LJ s'-N/2 exp - 11"1 N
s'-1
I\T J?
1 ~ . r-1)(s-l)
..;N ~ Ds exp . ~1I"1
N
1.3 Fourier Transformations 19
*N/2-s'+2
(ii) Generate the next line by appending the next-to-Iast line to the
last one.
20 1. Functions in M athematica
am-
YSICS
Let f(t) be a physical quantity that is measured at discrete times ti. The
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
9r = L9r-j+1 k j . (1.26)
j=1
N
.(8 - 1) (r - 1)
N
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]
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
. . . .. .
The result of the algorithm for smoothing data introduced above depends on
the width u chosen for the kernel. Calculate the smoothed data for a wide
Press W.H., Teukolsky S.A., Vetterling W.T., Flannery B.P. (1992) Numer-
, ,
Wolfram S. (1996) The Mathematica Book, 3rd ed. Wolfram Media, Cham-
paign, IL, and Cambridge University Press, Cambridge
,
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
(1.28)
2
o
P N
-
M
(X~) = r () / o
N-M
e- t t-2-- 1
dt. (1.29)
,
the possibility that our experiment belongs to those 1% of all cases for which
X2 is greater than or equal to X5. If, however, we had P = 0.9999, our fit
x2 (a)has a minimum for some parameters ao and the value of x2 (ao) falls
within our confidence interval. If we could repeat the experiment several
wan
1.5 Nonlinear Fit 25
aI, a2, ... . From the width of the distribution of each component of the ak
we obtain the error bars for the fit parameters ao.
,
it can be shown that the quantity L1 = X2 (a)
- X2 (ao)
is again distributed
according to the distribution function P from (1.29), this time with M rather
(1.30)
determines the re ion of allowed values of a. In arameter s ace the re ions
of constant L1 are ellipsoids. The projection of this (M - I)-dimensional sur-
face onto the axis i then yields the error interval for the parameter ai.
For the nonlinear fit, too, it is easiest to use the functions available in Mathe-
matica. To find the minimum of x2 (a), we use the function NonlinearRegress
rom t e pac e Statistics'NonlinearFit'. t 0 ers vanous POSS1 Illes
for entering data and initial conditions; in addition, one can change the
method of the minimum search and have the program display intermedi-
ate results. Of course, one can also provide one's own definition of x2 (a) and
oscillation
f[t_] := a Sin[om t + phi] Exp[-b t]
with four parameters a = {a, om, phi, b}. This oscillation is measured at
11 points in time ti for the parameter set a = {1, 1 ,0,0. 1}, and noise in the
form of uniformly distributed random numbers is added to the data:
om ,
{t, 0, 3Pi, 0.3Pi}]
26 1. Functions in Mathematica
0.2
/ x
2
dx
2
= 150 .
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]
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
, . ., z
We obtain the confidence interval for the value of X~ from
1.5 Nonlinear Fit 27
..,;)
0.15
~
V.I
/)J // // *l
0.12
OOR
0.1
I
/
-
'\
0.05
0
11/
f L..-//
l/
0.06
0.04
v.v..:.
~ ............
-
~J ..-/'
0
0.4 0.6 0.8 I 1.2 0.9 0.92 0.94 0.96 0.98 I 1.02 1.04
a om
'INa
'CO
1 111 n nf ,,2(.n)
"" , -~
T
UTifh fho ... _h .... 1"'.... 0 i ....
r .
space (left) and with the om-b plane (right)
If one vanes the frequency om rather than the amplitude a the compen-
,. .1 ~ hrn,p rlnp~ nnt 1 ~~ .1 in thp riCTht_h~nrl nf
'rr . '0'
1
Fig. 1.10. The true values, om=1 and b=O .1, lie close to the edge of the inner
confidence region; therefore, the confidence interval should not be too nar-
row If onp nlot.~ f rt: 1 for two v~ll1p~ frmn F'i IT 1 10 ,1. ;:1..:1 ~
J
..... v ~ ...
..J"
...."" .L~ a..uu
"" ........
CLv.~,
""
..... 'v, v.uoc; ~a.u ooc;oc; .L.U
D,'
.I.' .LE)
., .,.,
.1. .1..1.
.1.. ..... 1..
Ll.
lIua.lI UVlIU ~U.L
'11
voc;o OllU.l .loc;p-
resent the data relatively well. The small number of data (N = 11) and the
large error do not permit a better fit.
A -'I' -'I 4-1. 4- 1. .1. 1 , ,. 1 .
.< ... 0 ~.... u .. ~'" u ...."'v.. J , u .. ~"'.. '" ~o LW." V'" J.VJ.
estImatmg the errors OI the parameters. une taKes the optImum parameter
set ao for one experiment and uses it to generate new, artificial data that
are fitted in turn. Repeating this for the same ao yields a set of parameter
vectors ak. Figure 1.12 shows the results of 100 iterations, using the ao from
(1.31). together with the contours from Fig. 1.10. It can be seen that in the
(a,b) projection even more than 90% of the data fall within the outer contour
I /""'\.
'" ,.,
V.1J
. l \
';:;'
.....
0.25
0.5
~
v
V
H ~
A ,.
4
-0.25
-0.5
0 2
V 4
..........."
6 8
Fig. 1.11. Two fit curves
~
lIt:u,
, ~-
I'
UV.lll
J.,J.VJ.""
lI.l.lt: VUlIt:l'
r
~Vll-
-
liour OI line a-D plOli snown
t in Fig. 1.10
1.5 Nonlinear Fit 29
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 '
Exercise
+a exp
data = tvinpeak.dat
fit parameters.
30 1. Functions in M athematica
Bevington P.R., Robinson D.K. (1992) Data Reduction and Error Analysis
for the Physical Sciences. McGraw-Hill, New York
, "
Press W.H., Teukolsky S.A., Vetterling W.T., Flannery B.P. (1992) Numer-
ical Recipes in C: The Art of Scientific Computing. Cambridge University
am-
exact potential.
ysics
OX' oy' oz
When observing this potential from a long distance, Le., for Ir - I
r(i) ~ 00,
4>(r) = -
r
+ - r 3 + -rQr+O
2r 5
(1.34)
1.6 Multipole Expansion 31
N N
q = ei, P= ei r (i), Q kl =
i=l i=l
where ri i
) is the kth component of r( i) .
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}]]
two vectors,
ei = 1 and:
32 1. Functions in Mathematica
...
..
1 c:
~
1 $
0.5 Ss
""
>. 0 a:"'.....'J7
'V'J
EIb
~
S
-0.5
-1 $
-1.5
....
-... ,
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2 Fig. 1.13. Positive and negative charges
x randomly distributed in the x-y plane
We present three ways to visualize this result: first we use Plot3D to plot the
r. r .. r
r
.1
,U.l
,'I..
lJ.l.l{;; .lV.l.l.l.l V.l
.11
" ............ J'" (ld..lU
..1
~ VUlJ V.l
.'1..
lJ.l.l{;; "'" -Y A
1
,
next, we plot the contours 01 thiS mountaIn range lJy usmg (;ontourPlot;
finally, we calculate the electric field and plot it via PlotVectorField, from
the package Graphics" PlotField'. In order to see anything in the latter
case, however, one has to normalize the field, i.e., display only its direction.
The dinole and auadrunole moments can be formulated lust as easilv in
Mathematica. According to (1.35), we have
dipole = Sum[r[i] - r[i+5].{i.5}]
.. ......:.....,_r_, ._
r~-- ..r r,~" . r r .. " T~ r" __" ,.., r,o .... r ...... ,
q~wn
_.. . 'L'" ... L L .... .J .J
-~
~ .........
... L L ... .J .J
i LLL~JJ -
...... L ....'
~
' ............
-~
~ ..
v.J.~
...
........ .I.~ ........I.J
_....
'LL'L~"OJJ ,"l~,OfJ
r. _ , ..
With this, the expansion (1.34) of the potential 4>(r) can be defined immedi-
ately. In our example, there is no net charge (q = 0); therefore, the first term
pot 1 is the dipole term, and pot2 contains the quadrupole term in addition:
po'Cllr_J - Q1p0.1e.r I magnlrJ,j
pot2[r_] = pot1[r]+1/2/magn[r]A5 r.qsum.r
, .~
.lV.l l.J.l{;;V.llJ'y, V.l ,0 vv .llJ.l~ a..l.l a..l
'.1 V.l
indices (= nested arrays). Therefore, in this case the quadratic form "vector
1.6 Multipole Expansion 33
conventIOn programmmg
nest two for loops:
e ie =
-{D[pot[{x.y.z}] ,x] ,D[pot[{x.y.z}] .y] .D[pot[{x.y.z}] .z]}
Results
,
randomly distributed in the x-y plane (Fig. 1.13). In this plane they gener-
ate the potential pot [ {x , y , O}] that is displayed as a "mountain range" in
Fig. 1.14. The potential .p of the ten unit charges in the plane z = 0
34 1. Functions in M athematica
not correctly represent the two positive maxima near the positive charges.
Even with the quadrupole correction (long-dashed curve) the approximation
.
Exercise
_
_
----//////Il
- 1// / / I. 1 \\ ~\ ~\ '\ " " "," ---
\ ",,,,,, - - Fig. 1.17. The direction
... ---//// / / / I l
-10 ----//////1111 \ \ \ \ '\ " " " " ' " of the electric field of the
~\\\\'\'"''''''
ten unit charges in the
11) 11) n
v
takes a particularly simple form in spherical coordinates (r, 0, t/J), with unit
vectors er , e(J, et/J. Only its t/J component is non-zero, and for this component
or..... or
Lilt: uy J.U. gl vt:~ Lilt:
k2 = 4ar sinO .
a2 + r + 2arsinO
2
Calculate the magnetic field B(x, y, z) and plot its direction in the x-z
plane, using the function PlotVectorField[. .. ]. Attempt to plot the field
1:~" ........~ D :~ 4-\.. ..... ~ _.1 \.... ~ ..... :4-~\..ln no 1
nint ~applies
omy to Mamematica versions oeIOre .l.U): ~ne prOOlem tnat
Mathematica does not know how to calculate the derivatives EllipticK J and
EllipticEJ can be solved since the derivatives of the elliptic integrals can
be expressed again by elliptic integrals. The two lines
. . - - . . -- . .--
36 1. Functions in M athematica
Gradshteyn I.S., Ryzhik I.M. (1994) Table of Integrals, Series, and Products.
Academic Press, Boston, MA
ml ., ac man
Addison-Wesley, Reading, MA
Wickham-Jones T. (1994) Mathematica Graphics: Techniques & Applica-
Work = force x path length. This seemingly simple equation from high school
.. ...
p t;
F= -vp. (1.37)
s in space r
Sin[2Pi t] t}
1.7 Line Integrals 37
The first path is a spiral, the second the straight line connecting the two
points, and the third a semicircle in the x-z plane. ParametricPlot3D dis-
int[r_]:=Integrate[k[r].v[r].{t.O.l}]
cur
o O}.
38 1. Functions in M athematica
r 1
o o
where we choose s (t) = r4 = t {x, y , z} as a path from 0 to r. Except for
the si n int [r4] ields the otential ~ x z = - x + xz
We can now slightly modify the field F(r), for example to
f[{x,y,z}] = {2x y 2 + z 3, x 3, 3x z 3}
A A A A
,
now calculate the curl again, then curl [f [ {x, y , z}]] yields a value different
from 0, in agreement with the dependence of the integral on the integration
Exercises
, , ,
three line integrals and plot the absolute values of the three accelerations
Id2r/dt21 as functions of T.
. .
Literature
cations, Mineola, NY
,
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.
pV = NkBT. (1.39)
Here, kB is the Boltzmann constant. Taking into account the interaction
,
function of the volume V for constant temperatures T. For high temperatures,
the pressure decreases as the volume increases, whereas for low temperatures
(1.41)
Sa a
T = 27NkBb' ~
c = 3b, Pc = 27b2
(1.42)
, ,
i.e., over a certain range three volumes Vi, V2, and V3 correspond to each
pressure p. Fo~ thermodynamic reasons, the transition_ from the gas, with a
40 l. Functions in M athematica
Vft
Jr p( V)d
- -
V = Pt
1-
~ V3 -
-
VI) .
\
(1.44)
VI
~lJ Pt, _ga:s ~IlU
. ..nqulU.. are
. . .ly .. "
lur
.. .
au v
T-P
V
..
WllJn
VI < V < V3; one observes a two-phase mixture. Geometrically, the equa-
tion above means that the ar~a bet~een the curve p(V) and the straight line
Pt = con~tant in_the range Vi to V 2 is the same as the corresponding area
between V2 and V3 (see J:4'i~. 1.19). Usm~ Mathematzca, we want to construct
+h~ .ii.
- ~
+_h~4o ,~
. .l., ... ",,,,,, linp
-
t'Irst, we venty l1.4~) tor tne cntiCal pomt. we enter tne van aer WaalS
equation (1.40) (NkBT = t):
.n=t:/(v-h) - ;t/v-?
....... A
~ .... ~
' ,.. ~ ....
lo 'h.n lo.nn
~ ~
.. (1 111\.
\ '/
eq1=D[p,v]==Q
eq2=D[p,{v,2}]==Q
TT , , , ,. , , ,.
nel-e, LIlt: OJJ ...... ..,,,.. au ~
,w Lel:iLl:i Lue . "'
and is executed first. We solve these equations for t and v:
sol=Solve[{eq1,eq2},{t,v}]
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]]
For the two-phase line we need two equations in order to determine the two
unknown volumes vi and v3 between which gas and liquid coexist. The first
.
.. ""',,"
-J
t'h",t ,~
"'1 ..
an" '" H t" nf~ r
eq3=p[v1]==p[v3]
1.8 Maxwell Construction 41
'1"'1-. ~
.&. ........
.J ~~~
""........ ..
.. 1-.~ .. ~.~ ~_~~~
v........ v
.... ~ {1 AA\
""................... ..............""............. 0 V"" \.L ..... J
eq4=p[vl]*(v3-vl)==Integrate[p[v].{v,vl.v3}]
An attempt with Solve indicates that Mathematica does not find an analytic
solutIOn. '1'heretore, we wil1 use FindRoot to obtam a numencal solutIOn. '1'0
find a reasonable result, however, the initial values of the (vi, v3) search have
to be specified rather precisely. Therefore, for temperatures T < 1 the function
plot [T _J first determines those values of v where p [v] attains its local min-
. . and ~ thp. . of thp.
and .. V~IV
1 .-t.
.. ... .. I. ~ l I r il.
'1"'1.
V"''''', V" ....... " .L ............. v .........
i' .J '" . , r. r ..'
.... v~V .... L'p LV.I
r ..... ., .,
-.PLV" ....... ".I ,V.I .. ,,-
turns three solutions; the two outer ones are suitable initial values. The final
Maxwell function then is
"Dmax[v J:= If[v < vi II v > v3. "D[V]. "D[v1]J
Thus, if v is between the solutions vi and v3, the two-phase line is returned,
otherwise it is p[v]. Fig~re 1.19 shows the result for various values of the
normalized temperature T, together with the unphysical functions 'P [v]. As
'IT _~ 1 /1.
'. iho'l '1"1(17\ in tho CT~'l
., r, I
tho 'T'ho tnn
.....
.... ..... O'
phase, and the next lower one represents the situation just at the critical
temperature. The three lowest curves show the separation into a liquid (small
, .
J.J.J.
, . .) ~mrl ~. .....
~"i' ... , . . .1- A )onu t.hp .. ~.~
..... . .1- linp 1"
.. '.J ~.nrl U~R
.....
--
1. IJ
1.5
1 ')l\ \
\ ~
\~-~
c.. 1
0.75
f\,
~.~ --
\/
/
~......-.-..
0.25
0
\/ 1 1. j 4 )
"":... .. .. 0 l\Jf
.. ~~_ ..1-." u .... ~ ..:1,,_ "'X7........ 1... T... ~ ..- ~~_ ..1-."
0 _e
,.
--
,
-s.-
,;:,
oL
~
.L
~~.
.. ~ ..
.vtJ, .v, .L
v .... ~
~ ~ ~~
~ ....
v.~tJ, v'~"',
~~"
~~..
~
-~
~~ ,
~'1'
q
Calculate and plot all energy levels en as a function of the parameter x.
1, ew or
Schmid E.W., Spitz G., Losch W. (1990) Theoretical Physics on the Per-
sonal Computer. Springer, Berlin, Heidelberg, New York
Mathematics
, . .,
o
1 3 1
K= -1 10 4 2
7 -2 3 7
Since the gain of R is the loss of C and vice versa, this game is called the
two-person zero-sum game. This procedure is repeated many times. At the
Now what does a gain of 3 mean to player R, who, with this strategy, may
expect a minimum "gain" of O? And should player C, who would have had to
count on a loss of 4 in the worst case, be satisfied with 3? Indeed, player R has
ever reason to rethink his strate as closer ins ection of the a out table
reveals that, if he randomly chooses rows 2 and 3 with the same frequency,
his gain will be at least 3 for any choice made by C. And if he slightly prefers
row 3 in the rocess he will even exceed the ain of 3. One can see from this
j
the three frequencies PI, 112, and P3 (with PI + P2 + P3 - 1), according to
which he chooses the rows without any correlation. On average, he receives
K = 2: Pi qj K ij . (1.46)
i,j
44 1. Functions in M athematica
This is the famous Minimax theorem, which J. von Neumann proved in 1926,
at the a e of 23. We want to ut the meanin of 1.49 in words: if la er R
chooses an optimal strategy p~, ,pg, then his gain after very many moves
is at least K o for any strategy ql, , q4 of player C. This means that for any
choice 4 with i > 0 and 1 + 2 + 3 + 4 = 1 we have
i,j
From this inequality, one can derive a system of four conditions, since with
o
Xl,X2,X3 Xi _ ,
WI e 1m
= Koxo and the associated average gain K o are determined by a
strategy Po
minimum of c . x with the added condition KT x > b, where the latter vector
o.
i,i
This means that in the worst case player C, using an optimal strategy, will
c = {1,
1, 1}
b = {1, 1, 1, 1}
k = {{o, 1, 3, 1},{-1, 10, 4, 2},{7, -2, 3, 7}}
and
LinearProgramming[c,Transpose[k],b]
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.
(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-
,
of a linear differential equation. The solutions of this equation are wave func-
tions !P(r), which assign a complex number to every point r. More specifically,
48 2. Linear Equations
Physics
,
in the quadratic potential V(q) = mw 2q2/2. Here, q is the spatial coordinate
of the particle. In dimensionless form, the Hamiltonian of the system is
Here, the energies are measured in units of liw, momenta in units of ../limw,
and lengths in units of JIi/(mw). The eigenstates Ii) of Ho can be found in
. . .
The c~ are the energies of the eigenstates of H o, and the matrix (iIHolk) is
diagonal because the eigenvalues are not degenerate.
. .
H = H o + Aq , (2.3)
and try to determine the matrix UIHlk). To do this, it is useful to write q as
. . t
v'2
where a and at have the following properties:
a J =
a 10) =0 and a Ii) = VI Ii -
1) for i > 0 . (2.5)
Consequently, the matrix representation of q in the space of the unperturbed
The construct Ihs : = rhs /; test means that the definition is to be used
Results
o
3 (2.7)
o 1.
2
+ 154 ).
Its eigenvalues are
~
Q ~
~
8
7
>.6
~5 ~~
~ 4
3 ~
2
1 ---
0 0.2 0.4 0.6 0.8 1
ut:::i lUl'
. ,..
Fig. 2.1. Approximate val-
Lllt:
ergy eigenvalues 01 tne quan-
tum osCillator with the an-
'"
luur t:ll-
How accurate is the approximation? This can be seen in Fig. 2.2 for
the example of the ground state energy co. For an anharmonicity parameter
A = 0.1, co is plotted as a function of lIn, for n = 7, ... ,20. Obviously this
function is not monotonic. Althoue:h we do not know its asvmntotic behavior
4o'h ....
WAA~
. 1.
~A~~
~"''''....
&~A 'v
~ "" non h ....
~- ~~A ~~ 'S:
'r> .1 U ...."'U
~AJ A
. 1
".
llu
- J
.
~~AAAO
4o'h ....
~AA~
.1 .
-
u. OJ OJ\} lOj
0.55914
-.
S
UJ n r'r'n1,.,
V.JJ7~J
10 ____
Q ----
-
_==---------
'1-/
3
2
1
~lg. ~.3. The nve lowest en-
Exercises
1 nr~.w t.hp ~
.1
2. Calculate the four lowest energy levels.
3. Plot the wave functions of the four lowest levels together with the poten-
t.i~J
AI A " y y .,. y r 2 -' 4 y. ,1 L
"%. '-J'uc "au CWOU lIUC U.L '1 CW.lU '1 LJ UJ C,A-
T,'
Ohm's law is a linear relation between current and voltage. It is still true for
monofrequency alternating currents and alternating voltages, if capacitors
an In uc lve COl s are represen e y comp ex lmpe ances. e equa Ions
even remain valid for the general case of passive electrical networks, if one
chooses an appropriate representation for currents and voltages in complex
space. For a given frequency, they can be solved relatively easily by com-
uter and with the Fourier transformation the out ut volta e can then be
Physics
iwt
where Vo and 10 are complex quantities whose phase difference indicates how
much the current oscillation precedes or lags behind the voltage oscillation.
where R, C, and L are real quantities, measured for example in the units ohm,
farad, and henry. In an electric network, the following conservation laws, also
known as Kirchhoff's laws, are valid:
wing 0 ar e conserv i n, in
to the sum of the outgoing currents at every node.
2. Along any path, the partial voltage drops across each element add up to
the total voltage over the path.
R ...T.
~
I
Ie IL
c::>
'1'I ,., c::> T 'T
'-' 01
.LJ
Yo
01
I
r Fig. 2.4. Series connection of re-
slstance ana ~v oscUlatory Clr-
CUlt
transient, have the same frequency as the input voltage. In this case, the
. ...... .
t"
~
..
~ '0 "' . ..}.,. ".....1.-:1.......
Voltage addition: VR + Vo = Vi ,
Current conservation: IR = Ie + IL ,
.......
vnms
. .
laW.
9 P
VR - n lR,
~ Y ,- -
~..I:;.u:)
1
Vo - :-c le ,
lW
Vo = iwLIL .
.ror a given input VOltage Vi, tnese Dve equations, wnicn in tlllS simple case
are easily solved without a computer, determine the five unknowns VR, Yo,
I R , Ie, and IL. Independently of R, the magnitude of the output voltage Vo
always reaches a maximum at w = l/VLO; at this frequency the impedance
of the oscillatory circuit is infinite.
TTl 1i'1.... ') ~ . u.rO h~"o
. _1 _1 tho
h"
_1 _1" . . . If",
0' - - oJ -0 '"
capacitor 0 and an inductance L are connected in series, then the impedance
at the frequency w = l/VLO is minimal. Consequently, we expect a maximal
14-~~,", fnr thl~ !:at thl~ 'T'hl~ 1~ "1
'''-
n .....
'-'
.
r
. oJ
1
h"
'J
I.o.l,u::
t" n
'11.1 0 LWU . .
Voltage addition: fa ( R + iW~ + iwL) + Yo = V; ,
C L
R
r--t J-
~OOOO'
l
C)I
C)I
Vi C L Vo
--
C)I
~ ......11:).
I: -'i.i.J.
.... -
,.J . ~
urrent conservation:
resistances R, Vo becomes much larger than Vi. This can be made plausible by
the following consideration: For low frequencies, the behavior of the parallel
input signals one obtains the corresponding superposition of the output volt-
ages. In particular, one can expand any periodic input voltage Vi(t) with
(2.14)
(n)
Wn = 21t"n T to obtain an output voltage Vo Wn
output signal is given by
the system of equations is solved for the specified variables. Because systems
of equations generally have several solutions, Solva returns a list with lists
ar
_Vi ((r-l)T)
= Vi (t r ) = N , r = 1, ... ,N ,
ourier trans ormation we 0
.(8 - 1)(r - 1)
N
or
N
1 .(8 - l)t r
Vi (t r ) = -- bs exp 21l'1~-~-
We cannot use the Fourier transformation itself here, but have to use the
inverse transformation instead, so that the sign in the argument of the ex-
N
8 = 1, ... , 2 '
, as can a so e seen
omega omega
-0.
c
0.1
. :
.
0.4 :
'0 OJ-L.~:~+4-+-.............-+-:;...++-0---+---;--1-1--1 % 0.2 :
> -0.1 : i > 0~:------1'--~--+----:----t----1
,
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=
= ~ (Iz Vi + IzVz)
1
=- z
where we have set Vz = ZIz at the end. For the ohmic resistance R, t e
power is accordingly ~(w) = IIR(w)1 2 R12. We compare this to the power Po,
which results if all coils and capacitors in our network are short-circuited,
i.e. i t e in ut vo ta e i is connecte nect to t e resIstor ,so t at one
gets IR = Vii R, and therefore Po = IViI 2 /(2R). The power ratio P(w)1Po
is shown in Fig. 2.10 for R = 10 f!. At both resonance frequencies the coils
and capacitors appear to be completely conductive, while at w = 1 ..jLC the
Exercises
connected directly to R
Iterature
SICS
n,
and t n be the displacements of the light atoms from their rest positions, and
60 2. Linear Equations
Fig. 2.11. Linear chain consisting of two types of atoms which are connected to
each other by elastic forces
mtSn = 1 (t n + Tn - 2s n ) , (2.17)
mt in = 1 (Un + Sn - 2tn ) ,
, ,
hold for every unit cell n E Z. For a finite chain consisting of N unit cells
we assume periodic boundary conditions, that is, we think of it as a ringlike
. .
,
invariant under the translations {Tn, Sn, tn, Un} --+ {Tn+k' Sn+k, tn+k, Un+k},
k = 1,2, ... , N, (2.17) can be solved by applying a Fourier transformation.
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
, ,
2
w (q) and the corresponding normal modes S(q) for a given value of q. In our
2.3 Chain Vibrations 61
M- 1 F8 = >'8 . (2.22)
gously to the electrical filters (Sect. 2.2), the general solution can be ob-
tained by a superposition of the eigenmodes. From the complex conjugate of
The coefficients elll, which are not yet determined, are fixed by the initial
choosing a = 1:
matt ={ { 2f t -ft Ot -f*Exp[-I q]}t
{ Ot -ft 2f t -f}t
{-f*Exp[I q]t Ot -ft 2f} }
{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
.. ..
..
..
.. 54(0)
53 (0)
e---- ;0
e---- .. 52 (0)
Exercise
V (r r)
D (Ir - r 1 - a .) 2
~,J -- -2 ~ J ~J ,
the sides and the roof, and aij = V2l for the two diagonals.
Calculate the frequencies of the vibrations for small displacements and
Literature
Linear equations can have intriguing solutions. This becomes especially ap-
parent in the case of a crystal electron in a homogeneous magnetic field. The
electron's ener s ectrum as a function of the stren th of the rna netic eld
has a complicated structure reminiscent of a butterfly. This problem was in-
vestigated in 1976 by Douglas Hofstadter. Amazingly, the differences between
rational and irrational numbers become evident in this s ectrum. We want
butterfly.
64 2. Linear Equations
Owing to the identity cos a = [exp(ia) + exp( -ia)] /2, and because the term
ex ia is the translation 0 erator that effects a shift b one lattice
Ecp(x,y) = ~O [cp(x+a,y)+cp(x-a,y)
+ ex
pIes cp(x, y) with the amplitudes at the four neighboring sites. For the y-
dependence of the wave function we assume a plane wave,
,
(= 1 in units of m). Here one can already see the difference between rational
2.4 The Hofstadter Butterfly 65
with
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
en-
o o o
q
'l/Jq/2 +r = 'l/J-q/2 - r = 'l/Jq/2 - r for r = 1,2, ... , 2 - 1 . (2.37)
('l/Jo, 'l/Jl, ... , 'l/Jq/2) T = 'l/Je of the wave function has the form
2.4 The Hofstadter Butterfly 67
o
Ae 1jJe = E1jJe, where Ae = o 1
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
. .
j=l,j#i ij
conclude that the eigenvalues fall between -4 and 4.
68 2. Linear Equations
P2 - Po
Pn (E) = (Vn - 1 - E) Pn-l (E) - Pn-2 (E) for n = 3,4, ... , ~ ,
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
{
e = 8.0*ie/MAXY - 4.0 - 4.0/MAXY
n = 0;
polyold = 1.0; poly = 2.0*cos(si a) - e;
if( polyold*poly < 0.0 ) n++
,
((1- E) values to a data file. The function gcd (p q) used in the third line of
J
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
, ,
to any rational number a = min (m and n relatively prime) with a small
70 2. Linear Equations
denominator n there e also others with a large denominator, there will al-
ways be a large number of bands next to those values of (J that correspond
o a sm enomma or. ny lrra lon num er can e apprOXlma e y a
sequence of rational numbers with increasing denominators. Consequently,
there will always be an infinite number of energy bands next to an irrational
number. This results in the artistic drawing which, given infinite resolution,
resists our ima ination.
Exercise
butterfly and conceive an algorithm which bridges the many large holes.
,
statements. Add to this a considerable mathematical apparatus in which the
concept of states has to be introduced and operators have to be explained.
only be occupied once. In this space of the multiparticle wave functions, the
Hamiltonian can be represented as a matrix whose eigenvalues specify the
ener ies of the stationar states.
analytic methods. But even a numerical solution is not easy to obtain. The
size of the system and the increase in the number of degrees of freedom turn
x q m-m mu p y m, w
sider an electron gas in a crystal lattice. In dealing with this problem, we
have to take into acc?unt both the repulsive Coulomb interaction between
the electrons and their interaction with the ion cores. A simplified description
otIS SItuatIOn, w IC stl contams a t e essentla e ements, was su este
in 1963 by J. Hubbard. Presently this model is being discussed in connec-
tion with high-temperature superconductivity. It is, however, still uncertain
whether this model exhibits superconductivity at all.
Ph sics
e vacuum.
ctct ... ct N
10) , (2.43)
(2.44)
(2.45)
, k
of electrons localized at lattice sites. The index k contains the number of the
site, and the quantum number for the z-component of the spin, represented
(2.46)
If two electrons occu osed to feel the
Coulomb repulsion
Unktnk.J,. . (2.47)
, ,q
M
H = -t (2.48)
k=l u
with Ck+l,u = cl,u and CM+I,u = Cl u ' For the order of the single-particle
states, we choose
ct+ 1{1,0, ... ,O}, {O, ... ,0, I}) = ct+cttCk+ 10)
= -ct t
c c
t
and
It M+
= -ctt 10) + cl t ck+ cM+ 10)
t
- It
= -1{1,0, ... ,O}, {O, ... ,O})
The following quantities are conserved in the Hubbard model: the number of
particles with positive (Nt) and negative (N.J..) spins, the quantum number
. . .. .
After specifying the numbers M, Nt, and N.J.. we use the functions
Permutations [. .. ] and Table [. .. ] to generate the list index, which con-
{{O,l,l}, {O,O,l}}}
*
s [plus [k, sigma] [arg]]
number 0 as well:
cdagger[k_,sigma_] [0]:= 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}]
k=l {n}
Since the sums are interchangeable and can be regarded as scalar products,
Results
2.5 The Hubbard Model 77
2u
, , , 3
-2
fivefold degenerate: 2 = 0,
twofold degenerate: 3 = 3t.
model. The average double occupancy rate in the ground state for M = 4
sites and the so-called half-filled case, i.e., Nt + N~ = M (in this specific
. ..
asM~oo
U/t
-0.4,..-------........--..--------......
....
(/)
8. -0.8
e.o
II)
-1
Fi . 2.18. Ground state ener er
site for the half-filled band. The
o 2 3 4 5 6 dashed curve is the exact result for
M ~ 00, the solid curve gives the
80 2. Linear Equations
...,.
' - & 0 ....
The z-component of the spin operator at the site i can be expressed by the
particle number operators nit and nq: Sf = (nit - ni.JJ/2. For the ground
I _\ 1". L TT." , .J.1 ,L 1I..r A .J 1\ T 1\ T n '
i:)IJaIJ'lJ IY I VI. IJU'lJ .u
., VVI.IJ.U .U'.J. "% i:)J.IJ'lJi:) a u u J. Yi J. YJ. .&I,
.',
the spin correlations (11M) ~~:1 (glSf Sf+llg) and (11M) E~:l (glSf Sf+2Ig)
as a function of U It.
TO
,~uu..L'lJ
1"1.
.. ,. .
Ul a ;:seL Ul
. ,.
LIlalJ l:unven gIven InpUlJ valUeS lJO
,. .
U.l~U
. . .
output values. Now if the output itself is part of the domain of the function
considered, it can become an input in turn, and the function returns new
output values. This process can then be repeated indefinitely. While there
are otten no analytic methods to calculate the structural properties of such
iterations of the form Xt+l = f(Xt), they are easily generated on the com-
puter. Obviously, one just has to apply the same function f(x) to the result
repeatedly. We want to demonstrate this with a few examples.
few analytic results on this, anyone can easily reproduce the iteration with a
pocket calculator. For certain parameter values of the parabola the iterated
, . ,
.
.
: .,
Ul LU
.~
-
.
1::)
..l 'n t1-.o "n't
.
.Y
.. .Yc;
1 'n o:>n
. ~,.. . ,.
Ul LIle OlJa.l'Lulg Value Ul
'1'1-.0 00.
'
v ~
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
(3.3)
T, ~ Too - tS (3.4)
'
From this we can conclude
I - 1-1
1-+00 T'+I - Tl
The number tS is called the Feigenbaum constant and has the value tS
,
extremely close values separate after just a few iterations and jump around
in the chaotic bands seemingly independently. For a quantitative characteri-
. .
(3.6)
The parameter ,\ is called the Lyapunov exponent; it is a measure of the
(3.7)
84 3. Iterations
immediately gets
Algorithm
2 Y ovn w
unknown variables x* and r" either by hand or by using the M athematica
function FindRoot. But we were unable to determine higher r,
values this
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:
~ .
l' or t -
~ J .. " ..' 4....
1
II l:lnrl ... l:l ....O .... "ll:ltorl ,,; l:l
r
1 = 9ii (91:"1
1
(9ii 1 (0)))
with
.1 , /1- 11
ana 9L
. .1 /1- 11
.
9R ~'fJ) ~'fJ)
V JL V JL
This finally leads to the following equation for JL:
I
a = 1/V a + ..v/ a - "fa (3.9)
JL=yJL+VJL-VJL-YP;
We have programmed the generation of the sequence in Mathematica in the
foP w~.v
., For p~("h ., .1. .1 R (T,) WI"
. t.hp mnnhpr~ 1 (I)).
, , t.hp ~p_
~
, "
quence of length 2n is stored as a list period [n] . Initially we define the list
period[1] = {c, 1} for n = 1, and the doubling of the sequence is done by
per1odln_J:= per1odlnJ-
Join [period [n-l], correct[period[n-l]]]
86 3. Iterations
sum is even.
correct[list_]:=Block[{sum=O,li=list,I=Length[list]},
Do[sum+=li[[i]],{i,2,1}];
If [OddQ [sum] , Ii [[1]] =0, Ii [[1]] =1] ;
Ii]
prec=30
maxit=30
In order to generate and display the orbits XO, Xl , X2 , X3, for all parameters
r (or J.t), one should use a fast programming language, if possible, since each
value of r requires about 1000 iterations. In principle, however, this is very
until the X n have come very close to the attractor. Then, one calculates
Xn ,
1000 additional values of X n , transforms them into the y-coordinate of the
xit = 4.*r*xit*(l.-xit);
putpixel( r*MAII, (l.-xit)*MAIY,WHITE);
following function:
3.1 Population Dynamics 87
}
getch();getch();clearviewport();return;
}
Results
fixed points of the fourfold iterated function f(x). These can be seen in
Fig. 3.2. The function f(4)(x) intersects the straight line y = x eight times,
but onl four of those are stable fixed oints. As T is increased attractors ith
, ...
Too = 0.89 .... This is clearly visible in Figs. 3.3 and 3.4, in which 1000
Xn values are plotted for each value of T, after an initial transition period
0.8
0.7
,....,
c:
~ 0.6
I...
I
I
~ L-----------:t:----~
.: ~~m; .. .;0; _-.... N ;;..,;;.~. ~~_:o-.. . . . . . . ~-. ~'~ ~_ ....
below a five-cycle; though there is just one band there, one still sees the five
peaks of the adjacent cycle. It can be shown that only one band with density
exists for r = 1. In Fig. 3.4, in the chaotic region, one sees many windows with
baum constant 8. To this end, we calculate the parameters Rl, at which there
3.1 Population Dynamics 89
0. .
/
/ V /\
0.6
/ /
/ \ \
f\A
~.
I / \
I /
0.2
//
1/ \
\
oV 0.2 0.4 0.6 0.8 1
Fig. 3.6. Superstable four-cycle
with r = 0.874640
1 /
/'
" /
0.8
0.6
/
/ V
/ \
"
"
0.4 I / \
I / \
0.2
/~
1/
\ '(
are
..
VI. LJUlt:) or .?~I II II
.. - - .1 ~
,(.'. I lSI 19 tne TTlPT 'lnrl~ or symoollc aynamlcs
. . . . . .
-0;-
R15 = 0.892486417932 .
3.1 Population Dynamics 91
~ = 4.669201134601
~12 = 4.669201587522 ,
~13 = 4.669201604512 ,
~15 = 4.669201608892 .
From this we estimate that we have calculated ~ to 9 digits. The extrapolation
the command
Nest[h, N[1/3],100]
n y m ,prec ,
can specify the precision via prec. Now Mathematica reduces the calculated
precision after each step until, finally, the variable X n is set to the value 0
92 3. Iterations
An
..
.
..
..
.
....
. .
. .. ..". n... rn1~ ,.
....
.: &5. u.o. ~ oUt:: ~" VJ.
..
. XIOO for r = 97/100 as a
(\ III 111111111111
.... is performed. The vertical
axis e:ives the number of
o 20 40 60 80 100 digits to which Mathemat-
ica calculates the result of
precision of the calculation the iteration
Exercises
1. Calculate the Lvapunov exponent for the loe:istic map (3.1) as a function
nf tho 'I"
r
n. T , . ,. ,1 , . 1 1
~. ~11 ~dt;11 1 J11L~J VdJ 11J L11~ <..I' L11~J~ dJ~ W '0 WJL11 _..- -
stable periodic orbits. Any such orbit starts with the symbolic dynamic
CRL. Therefore, there are at most four possibilities for a five-cycle:
rY~T~~ rY~T~T rY~TT~ _, rY~TTT r. r, .,_.,. . .
V.lI,.LJ.lI,.lt" V ,v auu v . ,-,Ut;; VJ. LUt::Ot;; ..- J.O
T -, ---
Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Red-
wood City, CA
'Q ... ;T; .... U 110QII\ ("'l'h ........'" "('XT. _,.J CI .r> roo
Jom fi.-J., .l\.orSCn fi.J. \1~~LJ:) .n;.UlS: i\. rrogram \..Jouecuon IOr "(;ne C"\..J.
Springer, Berlin, Heidelberg, New York
Ott E. (1993) Chaos in Dynamical Systems. Cambridge University Press,
~
\ .:.:ITrJ.U5t::,
_y _r.
l''1ew lurK
Peite:en H.O.. Saune D. (1988) The Science of Fractal Imae:es. Snrinlrer.
Berlin, Heidelberg, New York
Schroeder M. (1991) Fractals, Chaos, Power Laws: Minutes from an Infinite
Paradise. W.H. Freeman. New York
, oo~,., n . . . t:lHllnQ AnT
n ~,
H r.! (1 .,
1
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
Ph sics
between neighboring particles, on the other. Then the energy of a long seg-
ment of the chain containing the sites XM+l, XM+2,' .. ' XN is given by
n=M+l
All lengths x are measured in units of the period of the external potential,
.,
v (x + 1) = V (x) . (3.11)
In the rest position, all forces on any given particle cancel each other. There-
---=V (3.12
8x n
With the definition
this leads to
(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
N 1 N 1 2
H MN = K L 2 (1-cos27rX n ) + L 2 (Pn - u) . (3.19)
n=M 1 (27r) n=M 1
cles:
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
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]]
The phase-space diagram is generated with ListPlot. The energy and wind-
ing number are easily calculated from the state 111 = list [xO ,pO]:
vind[xO_:.0838,pO_]:=
( v1=xlist [xO,pO]; (v1 [[-1]] - v1 [[1]]) /nmax)
pnev = p+K/2./pi*sin(2.*pi*x);
xnev = x+pnev;
time in this inner loop, where these commands are executed very frequently,
but should be replaced by constants. In our program, however, the graphics
xs = fmod(xnev,1.)*xmax+10;
ys = fmod(pnev,1.)*ymax+100;
VIa
putpixel(xs,ys,color);
Results
n, n
This picture is independent of the ratio (J of competing length scales, since
3.2 The Frenkel-Kontorova Model 97
Fig. 3.9. Orbits in the x-p plane. On the workstation, a new starting point can be
selected b a mouse click and the resultin orbit is lotted in a new color
this parameter is not used in the iterated function. Each orbit has a winding
number w, which depends on the starting point and the periodic potential,
but not on u. The equilibrium constant u shows up only in the energy per
K
211"
2 + -21 (Pn - u)
(1 - cos (211"x n
2
(xn,Pn). Around these commensurate states, one sees closed orbits, Le., one-
dimensional ones. These states look almost the same as their commensurate
relatives in the centers of the orbits but each x oscillates about the corre-
98 3. Iterations
Mod[t[t[t[t[t[{xO,pO}]]]]],1] == {xO,pO}
w = 0.4 and a slightly higher energy than the periodic state. Figure 3.11
shows the quasiperiodic state in configuration space. For the particle at the
after Q = 5 iterations. The oscillation can be seen even better in Fig. 3.12,
where the X n are plotted as a function of n. In addition to the period with
0.5
0.475
0.45
x
3.2 The Frenkel-Kontorova Model 99
0.05 ~ 1\ ~ 1\
I \ I \ I \ I \
0.04 I' I \ I , I \
0.03
, I
I
.
0.02
0.01
,I }. J \ 1 \I \\1 Fig. 3.11. The same quasi-
,.-
.or ~4-~4-~ ~~ : _ ...,:_
~u~u..... ~~~_:
'> 1 fl
'1,
11 \1 If} &0' .., . . . .
"-
V n
~
1
&
-., "1
~
A
~
L1CU
. . ...Y
~,
VLl
\;L; J
lIV'p VI. till" ,.- -
no
V.U
0.6
.-...
=
'-'
>< 04
n_
v.~
~'Ig. 3.~A!:. Tne QlSplacement
X (modulo 1) of the nth par-
0 tide is plotted for the same
0 20 40 60 80 100 function as in Fie:s. 3.10 and
n 3.11
which we will not discuss here (see, e.g., Griffiths). Figure 3.13 shows h(xo,Po)
. .
m a Sllce or tne Xo Po plane lOr Xo nxea at tne valUe U.UOJO ana u - ~/tJ. ~ne
~
, , I~ -.- .
_1
..
.:lIO
~
('1,
&
1" v,
.
W ~ U) Uc:G:5 aU
n
VI IS Lel'lS , aUU ",vU .. '~~U aUY LWV ISLel'lS
LUel-e lIS
f\ f\')O
0.028
>.
tlO 0.027
~
o 0.026
0.025
U.U:l4
_.
~ Ig. Jnergy 01 a
O).~O).
~ ~
-
u.~ U.~.J U .J U .J.J U ... lOree-nee state wltn u -
0.4 and initial value Xo =
pO 0.0838 as a function of po
f\,
0.475
....
0 0.45
~
-!3
tlO
.5
0.425
nA
v.
:a
.5 0.375
~
0.35
_. -
~ 11::). O).~<:I:.
, , ..
Ul:S-
0.325
lianCe W OeliWeen neign-
0.2 0.25 0.3 0.35 0.4 boring particles for the
force-free states shown in
pO Fi~. 3.13
Exercise
For different values of K from (3.18), plot orbits in the x-p plane. For K = 0,
, ,.
von ~l ~ .U he ahle t.o nr;:J,w t.hem hv h::mrl 0'
~
how t.he 1 IU. L1.:"i.
the so-called KAM orbits, turn into islands or chaotic orbits as K increases;
calculate the winding numbers of the remaining KAM orbits. Attempt to find
the 1:l.Cl.t. ., ..1 orhit. in~t.' 1'. K.
v
Literature
JodI H.-J., Korsch H.J. (1994) Chaos: A Program Collection for the PC.
Sorinf!er Berlin. Heidelberf!, New York
Ott E. (1993) Chaos in Dynamical Systems. Cambridge University Press,
Cambridge, New York
Schuster H.G. (1995) Deterministic Chaos: An Introduction. VCH Wein-
.r<
u-
ho;1'Y1
'n->"
, l\TonT Vnl"lr
............
.n..D.
r .. ""'''''' ..... ,
~ .L::1::1U)
r-.
r r -
, TF ..... .. ,.
Vi
.r< T
Ph sics
Thus, by comparing the masses of two similar cubes with sides L and 2L,
one obtains
M1
with D = 3. For squares, the result is obviously D = 2, and for lines D = 1.
(3.25)
D =- lim ---"-'-
e~O
(3.26)
102 3. Iterations
square an e or a ine.
So, if we want to determine the length of a border on a map, for example,
we can take a small ruler of length e and determine the number N (e) of steps
n . n, we wou expec
L = eN (e) (3.27)
, a
are random vectors, whose properties are easily calculated. If (...) denotes
the average over many molecular configurations, we have:
where a is the distance between adjacent monomers. For the vector R between
the beginning and end of a molecule consisting of N + 1 monomers, we have
i=1
and therefore
i=1
and
an
. .
ImenSlOn
Select three points PI, P2, and P3 and a starting point qo arbitrarily dis-
n+I -
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
each other. The structure is self-similar: all triangles look the same, indepen-
dent of their size (of course, this is only true for triangles that are much larger
.. .
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
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.
xerClse
A Koch curve is defined by the following iteration: The central third of a line
Literature
Wein-
thinking.
3.4 Neural Networks 107
tecture, as well as from its function. Such algorithms and their realizations
in hardware are called neural networks and neural computers, respectively.
,
digits, recognizing engine defects by their noises, judging the creditworthi-
ness of bank customers, predicting stock prices, etc. It turns out that neural
Physics
Here, any neuron can have just two states: it is quiescent (Si =
= 1 . The coefficients Wi E Ii model the stren
(So = -1).
This is the biological motivation for (3.28). Mathematically speaking, this
. .
shown that their number is less than 2(N ), which, for N = 10, still amounts
to 1030
(3.30)
, ,
synapses which fulfill (3.30) also fulfill (3.29) perfectly, which is the condition
to be learned (Xj E {+ 1, -I}):
N
w .X =. -Xj
N
(3.31)
3=1
x p
correctly by the current vector w:
3.4 Neural Networks 109
This is the well-known perceptron learning rule, whose convergence was math-
ematically proven in 1960 by Rosenblatt: if the M examples (xv, Yv) can be
. . .
w* . Zv > C > 0 for all v exists. The constant c > 0 corresponds to the
smallest distance of the points Zv from the hyperplane defined by w*.
i I tis ou ter
, . .,
which we have w(t) . Zv < O. For each of these, the learning rule yields
1
(w (t + 1))
2
= (w (t)) 2 + N2 w (t) . z v + N2
1
(z v )
2
N'
Note that (zv)2 = Lj Z~j = N. Iteration of (3.34) from 0 to t, using w(O) =
<-
- N'
An estimate of the scalar product w* . w(t + 1) yields
1 c
N N'
which, iterated from 0 to t, leads to
- N'
Now we insert (3.35) and (3.37) into Schwarz's inequality
(w (t))2 (W*)2 > (w (t) . W*)2 (3.38)
(3.39)
or
(3.40)
110 3. Iterations
, ,
classified correctly. Thus, the perceptron rule can actually learn all learnable
problems perfectly.
where the average is taken over many inputs S. The value 9 = 1/2 is the
result of random guesses and the perceptron can not generalize in this case.
For 9 > 1/2, on the other hand, the perceptron has recognized a certain
re ularit in the exam les learned and has a robabilit of a reein with
"
We now want to use the perceptron for the purpose of time series analysis
and make predictions for the next step. We assume we have a sequence of
F = (1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1, -1, ...) (3.42)
In each step, the perceptron probes a window of N bits,
,
sequence, on the other hand, will always give a hit frequency of 9 = 50%.
3.4 Neural Networks 111
Algorithm
1. Read input:
the screen. The hit frequency in the form correct/runs* 100.0 is displayed
after each step, as are the values of the weights and the result of the predic-
e program.
The version nnf name takes the inputs 1 and 0 from the file name. At this
point, we want to show briefly how to pass arguments from the command
line and how to read a file. The function main now has arguments:
argc contains the number of words entered on the command line, in this case
ar c=2. The two arra elements ar v [0] and ar v [1] contain the addresses
1.
found");
Result
1010101010 ...
correct
111001110011100 ... ,
3.4 Neural Networks 113
prp.diction correct
hit pe:rcentage: 58.65%
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.
ential equations. For example in Mathematica, one can use NDSolve to solve
ordinary differential equations without knowing the details of the program.
,
obtains the following set of equatio~s:
116 4. Differential Equations
,
Yl = Y2
,
Y2 = Y3
,
Yn-l = Yn
,
y , ()
x l'1m Y (x + Llx) -
= ~x~o Llx
y (x) = f (x,y) (4.3)
If the vector is known at the oint x then its value after a minute ste
x + Llx can be calculated according to (4.3). This is also the essence of the
numerical method: The spatial coordinate x is discretized and an attempt is
made at calculatin at the ad'acent oint x + Llx as recisel as ossible
dimension n = 1, i.e., y and f each have just one component Y and I. The
algorithm to be presented can easily be extended to arbitrary dimensions
(4.6)
en
2
h 1 h3)
I
Yn = Yn+l/2 - -Yn+l/2 + II
-Yn+l/2 +0 (
Yn+l = Yn+l/2 + h I
2 Yn+l/2 + (h) 2
1 II
2'Yn+l/2 +0 (
h
3) . (4.8)
(4.10)
Consequently, this second-order Runge-Kutta method yields an error of order
3
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
x = v,
iJ = f (x, t) (4.15)
(4.16)
This means that the algorithm jumps back and forth between calculating the
.. . .
for h ~ OJ this is the idea behind the Richardson extrapolation and the
4.1 The Runge-Kutta Method 119
Algorithm
,
tively in this case. H J depends only on y and not on x, then (4.11) can be
written as
.=
Module [{kl, k2, k3, k4},
kl = h N[f/.Thread[y -> yp]];
k2 = h N[f/.Thread[y -> yp+kl/2]];
The function Thread assigns the corresponding value from the list yp to each
.
Yo via
RungeK[f_List,y_List,yO_List,{x_, dx_}]:=
NestList[RKSte [f, ,#,N[dx]]&,N[ O],Round[N[x/dx]]]
Here p is the angular velocity <j; and q is the displacement angle ep of the
pendulum. As in Sect. 1.2, ener y and time are measured in units of mgl and
by
120 4. Differential Equations
r rl. __":' ... ___,
....
... ......
fl'\ rl. __ ..: , ... __ _, _1'\ 1.
;.r... ~ r._" '''' ."', '.;.''' ...~"
"'1'1'''' "t'....oAoV.t'V", ""&U"'A, ... ~
Figure 4.1 shows the result. The curve on the left is the correct result for
an initial angle <Po = 1r /2. Without friction, the energy is conserved and the
Tl'llH:!t hA 1.1.' ., , (QAA ]:;'i 0'
.
, -, ]:;'nr thA nlnt nn tho riO'ht.
v-0 -I;" I;"
shows the result of the Euler method using the same step size h = 0.1. It can
be seen that this method gives a completely wrong result, since the energy
. :mn t.hp i~ not. .
ru:
'-'.I , W'V Lo....L
..-" . , r
.1.1
.
't'lT_
'Y'V o.uu
-l-l
a.
L_ _J:L"t_J:_
II'V.L ...... V.L II.L..'V "'V",U" P'l'
to the graVItatIOnal torce and obtam a SOlutIon ot the equatIons ot motIon oy
RungeK[{p,-Sin[q]-r p},{q,p}.{phiO.pO},{tmax,dt}]
In Fig. 4.2 we see that the pendulum loses its energy and moves towards its
rest position q = p = O.
,/ \,
0.5 0.5
\
P 0 p 0 I
-v.,J
J
-v.,J
\ J J
-1
-1.5
~ ~ -1
-1.5
~ ~
-"... 'A
I n
V A ..." - ..." I
-A
n I
"
q q
Fig. 4.1. Oscillation of the pendulum in phase space q = <p,p = <p. Result of the
Runge-Kutta method (left) and solution of the same problem calculated with the
~Uler methOd ~ngfl,t}, wmcn ODvlously gives a wrong reSUlt
1 ~ ~
/
/.....-
////..- -..... ""
~,,"\..'\
11(1f~~>~\\ \
0.5
P 0
~~
-0.5
-I
"--- .-/
. .
~. - ...... .,. .
-,. ..
.r II;' ~.~. J. 1l~ ::5i:J,1~1~_ a<:I
~~ ~~ ~ ~
",-,.J v.v A A.v
snown on tne leIt-nann ::51U~ UI
q Fig. 4.1, but with friction J-t = 0.05
4.2 The Chaotic Pendulum 121
mx = J-LX + ax - bx 3
,
the nineteenth century, that a simple mechanical system can exhibit complex
behavior. The idea that one merely has to specify the initial conditions as
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)
, ,
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.
cp smcp = a cos Wo
(J = Wo . (4.20)
endulum is now described in three-dimensional s
For the time interval, we take the period of the driving torque and consider
.h
WIt t = -21rj and = 0 1 2 . .. .
, .
the Xi. We can formally express this correlation using the step function e(x):
N
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
Inc .
e-tO
Now it can be shown that the following relation between the three dimensions
holds:
c
In practice the three dimensions often agree within the experimental error.
f[1] = y[2] ,
f[2] = - r * y[2]
main 0
{
t
yold=y[2J/ysc*yimage/2+yimage/2;
rectangle(xold,yold,xold+l,yold+l);
t=t+3.*pi;
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
,
back and forth between periodic and chaotic motion.
a is 0.7
xerClse
forced ,endufmu :
r - 0.25 Il .. 0.100000
.--.-.-_.'
eriod 7 X 211" W .
4.2 The Chaotic Pendulum 129
I~l~f
. .;,._ .......................
"---------
fore" pendulum :
r- 025 11 .. 1.300000
ree equa-
x= -(1 X + a yr ,
Z=XY-bZ.
Here, X represents the velocity of the circular motion, Y the temperature
system's behavior.
This system is interesting for various applications:
When does chaotic behavior set in? For r = 28, what is the dimension of
the strange attractor in the Poincare section mentioned above?
Literature
,
solids are concerned. In the realm of the microscopically small, only proba-
bility statements for the position and momentum of a particle are possible;
. .
ca e statIOnary c ro mger equation, an elgenv: ue equatIOn or t e energy
operator, which in the coordinate representation takes the form of a linear
differential equation. In principle, this equation can be solved numerically
USIng e me 0 s rom e prevIous sec Ions. ere IS, owever, a more e-
ficient method for numerically solving the Schrodinger equation, which we
want to illustrate using a simple example, the anharmonic oscillator. For the
Schrodinger equation we have the additional problem that the energy cannot
take all real values but onl certain discrete ones which are determined b
4.3 Stationary States 131
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
analytic at A = o.
132 4. Differential Equations
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
. . .
n, i.e., 1/1n = 1/1(x n), 1/1~ = 1/1' (x n), and so on for the higher derivatives. From
the Taylor expansion,
... ,
we obtain
With this we can calculate the complete set of 'l/Jn values from two adjacent
initial values.
keyboard input.
The integration step (4.36) turns into the function step (&x, dx, &y , &ym1) ,
n n-l
to change the values of x, y, ym! from within step, we have to pass the ad-
dresses of these variables, each of which is marked by an &. Note that in C
e argumen s.
With this, the calculation of 'l/Jn+l goes as follows:
double step(double double dx, double *ya,
xml;
(1.+dx*dx/12.*k(xpl;
xml=x; x=xpl;
yml=y; y=ypl;
}
134 4. Differential Equations
step size dx covered by the iteration loop for (...) corresponds to exactly
one pixel of the x-axis on the screen; (xs,ys) are the screen coordinates. The
ypl=step(tx,dx,ty,tyml);
ysnew=(l.-ypl)*YMAX;
if(abs(ysnew10000) break;
depending on the input, the value of e (= E), the energy step size de, or the
step size dx (= h) of the integration is changed.
The program schroedinger calculates and plots the wave function 1j;(x) for
...;i,.....~....
[6.22030088,6.22030093] .
In Sect. 2.1 we calculated the ener
t energy elgenv ue
Exercise
Literature
er-
Springer,
136 4. Differential Equations
So far, we have only considered differential equations for functions that de-
pend on one variable (time or position). Now we want to study a wave that
Physics
(4.37)
characteristic, namely
u (x, t) = -2 sech2 (x - 4t) , (4.38)
moves to the right at a velocity v = 4, not changing its shape in the process.
Such a solution is called a soliton.
-2 V
,.-..
("t)
q -4
'-"
==' Fig. 4.8. Two solitons
move away from one an-
-6 other. The numerical solu-
I .J: .J ~ .1 ..1.
"A"VAA \ ... .., ....... ';"'~ ~"I ,......A ..... " .... ~
t = 0, the two overlap to form the wave packet (4.39), whereas after their
encounter both solitons have resumed their original shapes.
We would also like to mention an interesting link to quantum mechanics:
The Schrodinlrer eauation with the Dotential V (x) = - N (N + 1) sech"~ (x)
1-. nn 7\T '-
& & ~.... ~
_1
,
~.... ,,~
.... '-'......
_1 . 1.
.,. AA.......AA
,,~.n. ~n~
'-'.LA..... ..... .......L
+1-..n. .1 . ,,~+1-.. ..... V ...nT
"AA ..... '-'.L "AA..... ... ....... ,
equation by using the methods of inverse scattering theory. Since the expla-
nation is too complicated for the scope of this book, we refer the reader to
tho ,. '" hn"t
.1"
au au
- --+ U~+l
1 ( .
dt - u~")
, - --+ ~
dx
(u i +I -ui ) (4.42)
at ax n n
- 3 --+
~
(dx)3
~ (u 3+::i _ 3u3+:.:l + 3U3n+ 1 - U3~) . (4.43)
aX n n n
With these substitutions, we solve (4.37) for U!.+l with the result
,
,; . U3+ 1 - u 3 u 3+::i - 3u3+:.:l + 3U3+ 1 - u3 "
U~+l u~ + at I ou~ t':l:':I:4)
dx (dx)3 I
138 4. Differential Equations
......
.lImS
.
~41
. .
IS ,weJ. -c
C;a0:3 U
.. , . ...
tU-;"Jj 0
.y r
..
rlIp.
~
III
r .
'J
and
. ..:I.' 1.
~~rv
l'
We . the 1i~t~ I'lJ.j+k).
A V
1 1''', 1
. ,~ .
for k = 1, 2, and 3 via uplus [k] =RotateLeft [u, k] and can then formulate
the integration step {u~} --t {U~+I} as follows:
Sl;eplu_J:=\.UOlUP.lUSlKJ=n.Ol;al;eLeXl;lu.KJ.tK.;jJ'J;
u+dtl6 uluplusllJ-uJ/dx -
(uplus[3]-3 uplus[2]+3 uplus[1]-u)/dx A3
plot2 [i_ : 3] lets us plot the result after i integration steps, using dx = 0.05
........ ...:1 ...:1+ - {\ {\Il
'V.'V_
. . . .A A ~ ~v
Figure 4.9 shows the result. After just three time steps, u(x, t) exhibits oscil-
lations, which are caused by numerical inaccuracies and "explode" after just
lIWV UIVl~
. ,. . A-
.
"."
.L lUi:), VI , Ii:) A
1
v ~A'V~
1 1
dllU l;dll ut:
1 1 1 1 1
Vll lIUt: UCLU
. .
algorIthm.
What went wrong? We have committed several errors, which we can avoid
by the following modifications:
1
.L.
TI'
.u.y a.
'1.
UJ.l' lIJ.U:;
_1. _1. l'
lI.1J.tJ
.
_1.
tJJ.J.UJ. 1..11. lIJ.J.tJ
. 1 . . ~~,
. .&_&_ -
tlOn ot a I at and a'~ I axr~ can be reduced.
2. The use of averages stabilizes the algorithm.
3. The step size dx chosen must always be large in comparison to dt.
0 ....... 1 r
~ I
~
I
0 -5
0
--
><
='
-10
Fig. 4.9. Integration us-
mg step[u] and step
sizes dx - 0.05, dt -
0.02. After just three in-
-15 tegration steps, one ob-
tains an unphysical re-
-10 -5 0 5 10 ",.. 14- 'T'l... ..l _'1. _1_,
.,
_.' --~
.1. U. A 0
n
A
U&&&'" UV ... & 0 ' -,,;v
4.4 Solitons 139
Ul = Uo
Then,
dx
1 - -I
(4.45)
2dx 6
One sees that in the second case, u~ can be calculated in such a way that
dx 2 u" cancels exactl . This reduces the error b one order in dx. In a
similar way, one can reduce the error of the higher derivatives by a suitable
choice of the coefficients. One obtains
Thus, with respect to the quality of the approximation, the algorithm used
where we have already substituted the improved version (4.45) for a/ax.
Solving for the components (U~+l,U~+I' . ), which we combine into Un+l,
. ..
a n + 1 _ an eikdz _ e- ikdz
n
- - - - = -va ----- (4.50)
dt 2dx
uin ~ !2 (u jn+ 1 + u nj - 1
) (4.52)
This ives us
j+l _ j-l
n n
only remain stable if the time step dt is chosen so that it is smaller than
the propagation time dx/lvl. Or, from the opposite perspective, the spatial
. ..
rically as well:
j i+l _ j-l
n+ n n
vdt . kd
= - 21 dx SIn x . (4.57)
a = - I. -vdt
SIn
. kd x (4.58)
ax 2dx
U ~ !3 (u in+1 + uin + uin- 1 ) ,
-
8x 3
---I..
--r 2(dx)3
( 3+
Un
_ 2
Un
3+ + 2Un3- - u 3n- 2)
lot3 i :9 :=
(Do[ufut=step2[upres.upast];
upast=upres;upres=ufut; time = time+dt. {ill;
Print [lltime II. time] ;
Plot[uu[x],{x,-10 . 10.},PlotRange->All.
Frame -> True. Axes -> None] )
is shown by the dotted curve. The wave trough u(x,O) turns into two soli-
tons that move to the right at different velocities. This becomes particularly
the large amplitude approaches the slow one. At t - 0, the two combine
to form a single wave trough, and after the encounter both resume their
142 4. Differential Equations
-0.2
10
ure 4.12 shows the numerical solution for the initial state u(x, 0) = -4 sech2 x.
In addition to the soliton that moves to the right, additional waves disperse
4.4 Solitons 143
()
-1
....-......
'\.
"-/'
/"\
, I
f
c;) _,.
q
-5
~
-3
Fig. 4.12. Results similar
-4 L ,. . ...". ~ n ,. ~.
an
. ..
bV bUVOOlJ &U
Inn,l~
. !:i{,a{,t: '(1,\,x,
.I: .If) "%.0, UUb &VJ.
-~
U) -
-q seen' X. In aaWtlOn to
-10 -5 0 5 10
the soliton moving to the
x right, waves are radiated
icantly in the process. Obviously, the length of the lists {u~}j:O increases
as 1/dx. The following exercise is intended to demonstrate that, at the same
time the maximum dt has to be reduced in nronortion to (dx)3 for the sake
..... ~ n4- ... h;l;4-u
"' .. v
Exercises
1..l.U::: ~'i
.
~A. ~3A .
..., .... ..., ....
- -- - 8x 3 (4.59)
8t
The discretization used here yields
rlf (",j+2 ,>",j+l ..L ,>",j-l ",j-2\
u n+l
J
-- u n-l -
J \ n n n n I
. (4.60)
(dx)3
Investie:ate the stability of this ale:orithm by usine: the ansatz (4.49) in
(L1 I{O\ , , tn (L1 ~7\ thiCl lO!llrlCl tn tho ,. ,
, .~
th!llt
T"\
..... , , -J .. ~ -
.
1 2idt [sin (2kdx) - 2 sin (kdx)]
a=--
a (dx)3
.
NumerIcally determme the maxImum J.L of I sm{2kdx) - 2 sm{kdx)I {p, ~
2.6), and show that, in combination with the requirement lal < 1, this
yields the stability condition
1 ~
,
mine the stability limit with respect to dt, for a given dx; i.e., approxi-
mately determine the maximum dt allowed as a function of dx. Confirm
Literature
, ,
Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Red-
wood City, CA
its motion is
,
back and forth regularly. This classical picture, which is based on the idea of
a pointlike mass with precisely defined position and momentum, no longer
that the stationary states in this case are standing waves. But what happens
to an initially localized wave packet that moves towards the walls of the box?
v w v p isperses,
and wild interference patterns arise from which smooth wave packets sud-
denly reemerge. Finally, the entire process repeats periodically with time.
Ph sics
,
which moves in one dimension in a potential V(x). Then 11/J(x, t)1 2 dx is the
4.5 Time-dependent Schrodinger Equation 145
,
coordinate representation:
Here, the coordinate x is expressed in units of the box's width a, and the
energy E in units of !i2/2ma 2 . The energies En of the stationary states tf;n (X)
are known from the uantum mechanics course:
n =n 1r , were
tf;n (x) = { y'2 c?s (nITx) for n odd _1 < x < ! .
(4.67)
y'2 sm (n1rx) for n even' 2 - - 2
146 4. Differential Equations
C2m-1 exp
m=1
00
, ,
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
the complex interference patterns. The results section shows, however, that
4.5 Time-dependent Schrodinger Equation 147
(4.74)
(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
Algorithm
Here, j and n are integers, and dx and dt are the step sizes of the space and
time coordinates. As before, we write the second derivative as
with an error of the order O(dx 2 ). Now we can discretize the time deriva-
.
IV, n y
.
1 V
however, does not conserve the overall probability "p x, t dx = 1, which
is not allowed to change with time. It is indeed possible to find a discrete
approximation of the partial differential equation that conserves the over-
all robabilit. To this end the discretized time evolution 0 erator must be
The solution of the Schrodinger equation (4.65) can also be written in the
form
The approximation
e- iHdt ~ (1 - iHdt) +0 dt 2 , (4.83)
W lC correspon
hand, with
4.5 Time-dependent Schrodinger Equation 149
(4.87)
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
-1
1/J~+1 = 2
2 + (dx)2 Vi - i (dx)2 - ai 1/J~+i + ~ - {}~ (4.91)
. . iJ!.-1
~ = f}~ + ;-1 . (4.92)
lated from the wave function tP~. To solve these equations, we need the initial
state tP~ and boundary conditions. Since we want to confine the particle in a
. .. . .
2
2 (. 2 (dx) )2 1 ) 1 _ 1
tPn+l + 1 dt - (dx V - 2 tPn+l - f}n . (4.94)
(4.95)
Since the boundary value on the right, tP~+1 = 0, is fixed, this allows the
calculation of the entire vector tP~+1 at the time step n + 1.
.. .
1. Choose an initial state tPb and use it to calculate f}~ according to (4.88).
2. Calculate the vector aj from the initial value given in (4.95) and the
recursion formula (4.92) .
. For all ositions calculate the variable b!. usin the initial value from
4. Use (4.96) to calculate the values of the wave function ~+1 for the
next time step, using the initial value tP~+1 = o. This also yields {}~+1
, " n , ,
{~} are complex numbers. Whereas Mathematica, as well as other languages
like Fortran, can deal with those numbers directly, in C one has either to
(4.98)
{
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
XQ = 0.25. As we have already seen, the wave has to return to its initial state
152 4. Differential Equations
On the screen, we can only display those amplitudes which amount to at least
1 2 2
20" (n1r - k) < In (1000) => n max ~ 35, v~~x ~ 100. (4.105)
(4.106)
For the absolute value of the difference between these two expressions, the
Ta lor ex ansion of dives the result
(4.108)
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,
and T /2. As shown before, two wave packets form at t = T /4, which move
towards and then interfere with one another (Fig. 4.14, right), and at t = T /2
154 4. Differential Equations
Fig. 4.14. The wave packet 11/J(x,t)1 2 at times t = T/12 (left) and t = T/4 (right)
Fig. 4.15. The wave packet 11/J(x,t)1 2 at times t = T/3 (left) and t =T/2 (right)
,
coordinate even more. This is because so far we have used the energy values
2 2
Ell = V 1r of the exact Hamiltonian H in our considerations regarding the
, II
and the corresponding eigenvectors cPt, which, of course, are subject to the
boundary conditions (4.93), are known as well, however:
4.5 Time-dependent Schrodinger Equation 155
156 4. Differential Equations
(4.110)
E v previously considered. This explains both the broadening and the time
delay of the wave packet in Fig. 4.17. By taking the modified energy values
. . . .
period.
Use the integration routine described in this section to calculate and display
the mean values (x), (P), and their uncertainties Llx, Llp as a function of
in its center. Try finding a numerical criterion for the tunneling time tT.
. . .
2
J
Lj=J/2 Itf;~'1
Wn = J j
2
.. .
IV' : II I [,f-'
,...
"al'
. ---t
.
---t l"U Ule L Le ---t
...., ..
~Ul::; 1::; Lue
of associations which gave an important method of computer simulation its
name. With the help of random numbers, one can use the computer to simu-
late, for example, the motion of an interacting many-body system in a heat
reserVOIr. As m the real experIment the temperature and other parameters
can be varied. The materials being modeled can be heated up or cooled down,
and at sufficiently low temperatures one can observe how gases liquefy, how
atoms in a magnetic material get aligned, or how metals lose their electric
r
. nr.p..
u. .4- 4-
.L.L'V.L'V
. .,n'V
, 4-
......L.LlJ
.,. 1..
lJV UO'V
~, ., .
lJV OlJUUJ ....v , y
.
-.L ~ r&&J~&~~
&
phenomena can be described with the help of random numbers. Some of these
models even have universal properties: The values of the critical exponents
+l. .... +
U&&.... u
-, :h", +l.", ,,; .........,.,
U&&~
..
."u,,~~
.... + .....l. n " " ,
.... u & U-L
.. n_",
....-L ~
+l.",
u .... ~
n .... ...,.",
~ ...... A&~
~"' ..
-L'U''' J
..............
~
"~
_. A
mrrerent moaels ana are even measurea in real materIals. ~ nererore computer
simulation is a particularly important tool for understanding the cooperative
properties of interacting particles.
If the sequence of numbers generated by the computer passes many tests for
randomness, it is called a sequence of random numbers.
(5.3)
c = 1283
m = 6075
rndm[r_] = Mod[a r+c,uU
The following command turns the vectors en into graphics objects and dis-
plays them on the screen:
5.1 Random Numbers 159
,
have to cover this segment of the surface evenly, except for a geometry factor
resulting from the projection of the cube onto the sphere. Instead, one can
Shov[Graphics3D[Map[Point, triple]],
. . J J
There are various tricks one can use to obtain the longest possible peri-
ods and good random numbers. One can nest several different generators or
use different types of functions f. Also, one can generate bit sequences by
generates a new bit, after which the sequence is shifted by one position for
the next operation. It is known, though, that such shift register generators
and Zaman found a class of simple functions that yield almost the maximum
period. They call these functions subtract-with-borrow generators:
values of s, t, and m for which the period can be calculated. For example,
the generator
r~ = (r. ,~- r . .-:1 - r.~1) mon (2 32 - lR) (fiji)
" ,
3 2 95
has a period (m -m )/3 == 2 Moreover, this generator is excellently suited
for the language C. In modern computers, the operation modulo 232 is auto-
'" A ~. _
matlCauy DUUt IntO tne arunmetlCS or J.l:-Dlt Integers. ;::'Ince \.. auows unslgnea
integers (unsie:ned lone: int). (5.6) can be orogrammed very easily.
Marsaglia and Zaman combine this generator with
Tn = (69 069 T n -l + 1013904243) mod 232 , (5.7)
maine)
{
...:a~ .. l.'~
,
- _.,
_-1\
.&o"'"fJ .&oJ
for (i=O;i<N; i++)
r+=mzran()/4294967296.;
printf (Il r = 7.1f \n",r/(doub1e)N);
}
x, y, z, and n are set to initial values which the user can change arbitrarily.
The auxiliary bit c has to be set to c = Y > z, i.e., in C to 1 (true) or 0
(false). Since this program was written for a computer that performs the
operation modulo 2.1~ automatically. mod(2;:S~ - 18) reduces to subtracting
18 from the difference (T n-2 - T n-3 - en-d. Of course, this only happens if
this difference is negative, as the modulo operation does not occur otherwise.
The next random number is the sum of the two generators (5.6) and (5.7).
no thp' nf -'- hun ::ITP thp
1 ,1 f".1 .~ .J ". ......1 fO .1. ,1' '.".1 '" 1 1 .1
<J V.L lJUC ..... J.., lJUC ,J;" V.L lJUC lJWU UJ.UJ. v J.uuaJ. ..... ,
127
about 2 . Therefore, this generator can run for about 1024 years. Since, in
162 5. Monte Carlo Simulations
gen-
If possible, one should look for a similar problem that can be solved exactly
and compare the numerical results to the exact ones. This provides a certain
105 steps.
Start with different sets of five initial digits and calculate the actual
(J' -
5.2 Fractal Aggregates 163
Literature
.,
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
mathematical theory for the diffusion problem, i.e., the random motion of a
particle. We want to briefly elaborate on a few statements and results which
- imensiona cu IC attIce.
vectors connecting a lattice site to its 2d nearest neighbors by L1xi, i =
1,2, ... ,2d. The motion of our random walker, which is at the lattice site
x at time t, IS etermme y teo owmg InstructIOns: ran om y se ect one
of the nearest neighbor sites x + L1Xi and jump there during the next time
step L1t. If we now put many particles onto the lattice, all of which jump
according to these same random rules, and designate the fraction that will
1 2d
U (x, t + L1t) - u (x, t) = 2d L (u (x + L1xi, t) - u (x, t)) (5.8)
i=l
(5.9)
ImenslOn
5.2 Fractal Aggregates 165
which means that the average size of the random path increases as Jt - to.
,
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)
1 a d-l a (5.13)
L1u = r d - 1 ar r ar u = 0 ,
u(r) = UQ (5.14)
,
ponent of the current density, ir = -'T/au/ar, is proportional to R1'n-;;'/r d - 1
By integrating this over the surface we obtain the result that the total parti-
d-2
equation:
d-l<D<d (5.16)
numerical simulations.
Algorithm
max,
the introduction of an annihilation circle skews the properties of the aggre-
gate, as it neglects the fact that the diffusing particle can get back to the
max
Rs ;::: R max from the origin - the actual distance is denoted by R - it
168 5. Monte Carlo Simulations
4.
Figure 5.4 is intended to clarify this algorithm once more. For a fast simu-
lation of the DLA cluster, we use the programming language C. The square
. .
is a cluster particle at the site with the coordinates rx and ry, whereas the
sites with xf=O are available for diffusion. For very large aggregates it would
certainly make sense not to store the entire lattice, only the aggregate and
boundar sites but to avoid the bookkee in that would be necessar in this
case, we choose the easier way.
ry=rs*cos(phi);
}
5.2 Fractal Aggregates 169
...:11 1\
~ .., ........ J 06&&&1" "
l-
int r;
r=random(4);
switch(r)
{
case 0: rx+=1;break;
case 1: rx+=-1;break;
case 2: ry+=1;break;
,.. ......... ':t ....... ~ __ 1.
'J . . ..
'
"-
oJ
.,
J
After each jump, the program has to check whether the particle is annihilated
(R > Rk). whether it has reached a site adjacent to the aggregate. or whether
!ll ClhArt
. (fl ./
\'
fl ,\
U/
Ar !ll lAnl1" " ,1 . " (J:/
\.
'> fl.\
U/
-'I tA h.o
~~- '0 u
performed in the next step. These four "ifs" in step 3 of the algorithm above
are tested by the function check () :
char checkO
.f
double rtxty;
x=rx;
y=ry;
,~ . -, t
.. J .
,
J:lor the cIrcle jump, a random vector of lenKth 1t -lts IS added to the posItIOn
_1
of t.hp ~
170 5. Monte Carlo Simulations
double r,x,y,phi;
phi=(double)rand()/RAND_MAX*2.*pi;
x=rx; y=ry; r=sqrt(x*x+y*y);
rx+=(r-rs)*sin( hi);
ry+=(r-rs)*cos(phi);
}
if(kbhit( stop=1;
svitch (check 0 )
{
case
case ;break;
case
case
}
Result
square lattice
5.3 Percolation 171
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-
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-
.
1 V, U Pc or 1 eren
0
.
lattice structures and cluster definitions? How does the average size of the
finite clusters increase as P is increased up to the threshold Pc? How does the
o custer sizes look like. Does the in nite cluster have a structure at Pc?
The governing laws in the vicinity of the percolation threshold Pc are
particularly interesting. For example, we define an average size R(s) of a
custer conslstm 0 s artic es
(5.17)
e average SIze
8<00
, 8<00
the cluster increases as a power of the length, and according to Sect. 3.3 D
174 5. Monte Carlo Simulations
a square with sides of length L. For each value of L, one obtains the number
M as a function of Pi this results in a whole set of curves. Scaling theory then
,
quantities M and L can be expressed by powers of either P- Pc or the variable
e e,
defined in (5.19). In doing so, L is measured in units of and M in units
5.22)
Ld
where Ld is the number of lattice sites in the d-dimensional cube with edges
d
(5.24)
,
tides. In finite systems, however, there is no phase transition, no sharply
5.3 Percolation 175
where f(x) = J(x 1 / V ). Consequently, the concentration P and the system size
L are related to one another close to the critical point p = Pc, L = 00.
The fractal dimension D is alread obtainable from 5.21 since for L
~ the finite system looks just like the infinite one. Therefore, (5.21) yields
M (Pc, L) tv L D . Thus one can numerically calculate the fractal dimension
D from the increase of the number M L of articles in the ercolation
?
,
ity 7r(p, L) of finding a cluster connecting two opposite faces, which therefore
percolates, in a sample of size L. Obviously,
(5.29)
(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:
double p = 0.59275;
int i, j, L = 500, prj
pr = p*RAND_MAX;
. .
I I
Figure 5.6 shows the result. One can see a pattern without any apparent
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
observe the growing cluster on the screen, we have written the algorithm in
C. First, we label the three different cases with the numbers 0, 1, and 2:
#define NOTDEFINED 0
#define OCCUPIED 1
#define VACANT 2
This list, which initially contains only the four sites next to the center, is
processed sequentially and receives new entries while this is taking place.
5.3 Percolation 179
=0 . i <T. . i ++)
f nr ( i
rn1r-i1= r.. 1rn1= r....1__r,. _11 =
-~-'-_.-
--
for(i=1;i<L-1;i++)
for(j=1;j<L-1;j++)
array L1J LJJ =NI IIIJI... ~NJ:.U;
arrayLL/2JLL/2J=U\.... UI"~J:;U;
list[O].x=L/2+1; list[O].y=L/2;
list[1].x=L/2 ; list [1] . y=L/2+1;
list[2l.x=L/2-1 list[2l.v=L/2
list r31 ,y=L /2 . 1 i st r31 ,v=T.l2-t w
=~.
putpixel(L/2, L/2, WHITE);
{
i=list[ky'PD].x; j=list[ky'PD].y;
definition(i,j) ;
". /* for */
} /* while */
Thus, the program loops through L and processes the list of still-undefined
, 1. .J ~:4-~~ 'T'l..~ ,. . ..:I _.I: .: _ .: .. .: __ ( .: .: \ l.... .1- ., .
'J U&uvu. .&. &&v ............ .&.......&. .. .&."'..... ,.&.'J' UU'-N.UU aJJ .....
wnetner tne sIte \.1., J) IS aueaay aennea. TlllS IS necessary oecause tne same
boundary site may appear in the list more than once. If the site is not yet
defined, step 3 is executed, and the site (i, j) is occupied if the random
number r is smaller than the concentration p. If this newly occupied site has
any undefined neie.:hbors. their Dositions are entered in the list above. and
the value of the variable count is increased accordingly.
In the program, this looks as follows:
V01Q Qe:r1n1,&10n\1n'& 1, 1n'& Jl
1.
double r;
if ( array [i] [j] != NOTDEFINED ) return;
r = randO / (double) RAND_MAX;
if( r < .n )
I
array [i] [j] = OCCUPIED;
putpixel (i, j, WHITE);
if( array[i] [j+1]==NOTDEFINED ) ,
.~. .~
'\.COunll TT ;.L1Sll Lcounll,.ruJ . X=1; .L1SlI Lcounll,.ruJ . y=jT.L; r
, P P
{count++;list[count%PD].x=i-1;list[county'PD].y=j;}
}
else array[i][j] = VACANT;
}
The program still needs to be supplied with the declarations, the graphics
initialization, and the input handling routine event () .
To begin, we use the first algorithm for the generation of the entire perco-
The concentration p and the lattice size are the same as those in Fig. 5.6. Now
one sees a percolating cluster, which exhibits structures on all length scales,
5.4 Polymer Chains 181
c
are generated almost exclusively.
xercise
Literature
MA
Stauffer D., Aharony A. (1994) Introduction to Percolation Theory. Taylor
medicine. But physics, too, has long been interested in general mathematical
laws concerning the properties of polymers. Even a single molecule which is
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
D=-- (5.37)
3
Subsequent investigations have shown that this formula is exact in d = 1,
2 and 4 s atial dimensions an that t e numeric resu ts or ie a
value for D which is only slightly higher. In d = 4 spatial dimensions, the
value D = 2 agrees with the one from the random walk, indicating that,
in this case, the rohibition of self-intersection is no longer relevant for the
,
by mean-field theory starting with an upper critical dimension d = 4.
5.4 Polymer Chains 183
Algorithm
Consider a growing chain and let Zi be the number of sites next to its head
that have not been visited yet. Then l/Zi is the probability that a monomer
. . .
(5.38)
, ,
are assigned a high probability. This cannot be, however, since each allowed
configuration must occur with the same probability in the correct statistical
WN' II Zi = 1, (5.39)
i=l
an consequen IS
simulation is
184 5. Monte Carlo Simulations
(5.40)
and that we can consequently talk about the first monomer unit, the second,
the third, etc.
the first monomer might point to the north, west, south, or east.
If we ignore the direction of the first chain link, then the unique charac-
e ements goes
... ",-,.u~vv
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
k=l
equation.
In our case, however, detailed balance is not valid, as is illustrated by the
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
, ,
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
, , ,
direction [2] contain the vectors (1,0) and (-1,0) respectively. Finally, us-
ing a uniformly distributed random number from the interval [0,3), truncated
. . . .
vector choice 0
{
. x;
Y j
188 5. Monte Carlo Simulations
.....
..
r .. , _ ......
.~ .... ,
r.''''
L"J A - , .. .l.U.ll L.LJ A,
direction[2].y=-direction[l].y;
r=random(3);
return direction[r];
}
~~ V&& .... ~ .... &U && . . . . . . . . . . . . . . ~&~.t', V&&.... U & v .... &U .... ~ V&...... && . . . . . . & ...... ~"" ~&&"" V&& ....
ft. ' . ~. .
are oy l;ne v(Wut:; ~ncr. un l;ne , l;ne . . al; l;ne lOcal;lon u ....& ....
of the tail is painted over with the background color and a new circle for the
head is added. The result is a serpentine motion on the lattice. All this is
ft.. ft
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
If very many particles interact with each other, qualitatively new properties
can be the result. For example, at low temperature or high pressure gases
. .. .. . .
s stems.
Is it possible to simulate thermal equilibrium and slowly cool down a
system on the computer? Can the simulation of finite systems describe phase
transitions? In this section, we want to investigate these kinds of questions,
This model has universal critical properties at the phase transition, which are
also found for many other models and measured in real materials. We let the
Physics
Z is the sum over all possible multiparticle states S, and each state is weighted
We want to describe the Ising model, a simple model for a magnetic sys-
tem. To this end, we consider a square lattice whose lattice sites are occupied
H = -J L SiSj - h L Si . (5.46)
(i,j)nn i
in which every spin that is parallel to the field has the energy -h < O.
5.5 The Ising Ferromagnet 191
w 0 mp I u In om u r. w v
one hundred hours of processing time available on a machine which needs
about 10- 6 s for each step of the calculation. This assumes that we have
,
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)
In the limit to --? 00, tl --? 00, this time average agrees with the statistical
avera e
(A) = LP(8)A(8) (5.51)
.
, 0
librium from its potentially unphysical initial state 8(0), and tt must be so
large that the statistical fluctuations of (A)to,ft are small. Both requirements
. .
ues:
(5.52)
Af can be positive or negative; the system selects one direction through ran-
dom fluctuations while coolin down. Since for h = 0 the ener is s mmetric
for T > Te . As in the case of percolation, see Sect. 5.3, there is a diverging
correlation length e(T) which is defined by the decay of the spin correlations
(5.54)
intricate theory of the renormalization group from the seventies (Nobel prize
for K.G. Wilson in 1982). The two-dimensional model (for h = 0) was solved
in 1944 b Onsa er. Conse uentl the universal uantities are known exactI
T.e -- !- 2 2 269 J
~. kB '
kB In v2 + 1
(. fi\ )
The specific heat C diverges as In IT - Tel. Thus the value a = 0 does not
mean that the specific heat remains finite at Te , it just means that it diverges
more wea y an any power 0 e . e v ue 0 e IS on y v 1 or
the Ising model on the square lattice, whereas the exponents are valid for
any two-dimensional system whose critical phase transition has the same
symmetries as the Ising model.
We have alread seen in the case of ercolation that a finite s stem allows
dimension 2, 3, or 4):
'Y 2 d-'Y/ v
vd+ a v d+ a v
Algorithm
and
(5.60)
(5.63)
The term hi is called the internal field of the spin Si. This finally enables us
to formulate the Metropolis algorithm:
5.5 The Ising Ferromagnet 195
,
models of statistical mechanics. We will also apply it to difficult optimization
problems in the next section. Because this method uses random numbers, it
,
at a constant energy (microcanonically) or use a trick to surmount high en-
ergy barriers. The Metropolis algorithm, on the other hand, is simple and
any arbitrary initial state, since the system always relaxes into thermal equi-
librium. At low temperatures, though, other initial states may have long
i = 1, ... , L.
196 5. Monte Carlo Simulations
void 8etT(double t)
{
- ,
bf[l]= exp(-4./temp)*RAND_MAI;
bf[2]= exp(-8./temp)*RAND_MAI;
}
With the Boltzmann weight factors bf [ ... ] thus defined, the innermost
loop becomes
for(x=l;x<L+l;x++) for y=l;y<L+l;y++
{
e=8 [x] [y] * (8 [x-l] [y] +8 [x+l] [y] +8 [x] [y-l] +8 [x] [y+l]) ;
if( e<O II rand()<bf[e/2] )
{
Ch=(8[X] [y]+1)*15;
poke(VSEG,v,OxfOOlch);
}
for(x=l;x<L+l;x++)
{
8 [0] [x] = 8 [L] [x] ;
8 [L+l] [x] = 8 [1] [x] ;
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.
,
size L, and for a r = ITi - Tjl L the correlations (SiSj) decay as a
power of r (a = lattice constant). At T = 0.8Tc , the system is magnetized,
Fig. 5.10.
ferromagnet in thermal
equilibrium at Tc
198 5. Monte Carlo Simulations
,
energy barrier of the order LlE = J L has to be scaled, since a wall between
positive and negative magnetization has to form, which moves through the
o ,
kBT = J, to ~ 10- s), therefore, we obtain T ~ 10 s, much longer than the
4 40
merically, even for the two-dimensional model (z ~ 2.1). Near Te , the fluctu-
ations of the magnetization not only become larger, they also become slower.
Exercise
,
particles can only be at the lattice sites. This is described by the variable
ni which takes the value ni = 1 (0) if the lattice site i is occupied (vacant).
. . .
particles are to repel each other so strongly that no two neighboring sites can
be occupied at the same time.
Literature
,
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
(5.66)
in Sect. 1.9. By adding more and more constraints one can eventually restrict
202 5. Monte Carlo Simulations
S = (XI2'
. . X13, X N -1 ,N) designates one of the (N - I)! /2 possible round
. . .
, ,
us how we should proceed: We have to heat up the system and then cool it
down very slowly. If the system is always in thermal equilibrium, then it has
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
for the simulation - here, t is the actual processing time - should fulfill the
inequality
w v , r
optimization algorithms, which work with populations of paths.
Before we discuss the details of the algorithm, we want to estimate the
i=l
For N -+ 00, the right-hand side can be written as N(r), where (r) is the
average IS ance e ween nearest nelg ors. e now wan 0 ca cu a e r,
neglecting boundary effects; to this end we consider a sufficiently large section
of the plane, in which cities are distributed with a density p = N / L 2 Let
w(r)dr be the probability that the nearest neighbor has a distance between r
and r dr. In other w s r r i th fin i r
,
the circular ring with the area 27rrdr:
r
w r dr = 1- 27rrdr .
o
This integral equation for w(r) can immediately be transformed into a dif-
. r
resu ts III
1
Eo>
-2
-LVii. (5.77)
can only be determined numerically; for example, Percus and Martin find
e= 0.7120 0.0002 in the limit N --t 00.
Algorithm
(5.79)
ways of turning a round trip S into a slightly changed path S'. For the sake
of simplicity, we will only present the following one: we randomly select a
. .
S' = (i 1 , ... , i p - 1, ip+l, ip+I- 1, ... ,ip, ip+I+ 1," ., iN) (5.80)
ber r E [0,1] is less than the Boltzmann factor exp [- (H(S') - H(S)) IT].
5.6 The Traveling Salesman Problem 205
2 2
6 6
4 4
if(argc>l) N=atoi(argv[l]);
The order in which the cities are visited is stored in the array int path [N] .
llhile (! done)
anneal(path)i
if(count++ > DRAW)
{
206 5. Monte Carlo Simulations
The function event () examines the keyboard buffer. While the program
r uce e p eng
The function anneal (path) calculates the next. Monte Carlo step. The
position pos and length len which are needed in order to generate the new
, ,
If 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);
V li:L
Tne new patn IS generateo oy nrst copymg tne 010 patn toP) to tne new
one (np). Then the order of the cities between pos and pos+len is reversed.
The code for this is
....... .,; ...I - 'L
.....
( .,; _+
'
_ .... rl
r" J '
.,; _+ ......... rl
-r" J '
.,; _+
r ,
............ .,; _+ 1 .._'
-,
r
L
.LUI. .L'J.
.
memcpy(np,op,N*sizeof(int;
j=len;
for(i-O;i<=lenji++)
{
np[(pos+i) Yo N] = op[(pos+j) Yo N];
j--;
"\.
.
1.
.J
for(i=Q'i<N'i++)
.(
-i=(-i-&o1
J
"Iv.
dx=map[path[i]].x-map[path[j]].x;
dy=map[path[i]].y-map[path[j]].y;
,
1 += sqrt(dx*dx+dy*dy);
r
return U) j
}
Additional functions called drawDath and Drint draw the oath and write
fo.... + +". +1-. ..... .1. . .J , A 4-"+",... .,. ,,... +1-.",
...'"
v~ v
, .
VAA~.... .L
'~u~""
.. ~AJ'
ljIle
4 . . . . U~ . .
. on ljue
A.
~ U4"~
..
1"'A " b A ~".LA
ana
~
Results
We have read the data from travel. dat into Mathematica and plotted them
there. Figure 5.13 shows the randomly generated initial state of about 100
ritipQ Thp. .H'7prt nath P from f.~7R) h~~ thp V~.111p P ,..." 4.R WI"
~4-
L:JUu..LU
4-
..- ~4- 1-
n .. u .... u. -
A
T
1
In D.
~
1
... 1-
...... .... 1 v .LJ v ......... au " ......'"
'. 1- ~'L . .1- .
v .......,J ...... 0 .... 'r , ..... ".........
system quickly relaxes to the value l ~ 2.2, with about 20% of the attempted
208 5. Monte Carlo Simulations
Here the reader is to try and solve the optimization problem from Sect. 1.3
with the methods of simulated annealing. A signal with a given power spec-
. . .
, ... , ,
voltage H(S) = maxr IUrl. In each Monte Carlo step the configuration of
phases is modified randomly, for example by varying one randomly selected
Literature
A. First Steps with Mathematica
.. I ,7 . 7 ..
.l::S ollaJ.lI\Ju W.lL.l.l
L.l.l~
7 . U.l.l
7 ..
iU.l ..
-
.
Un systems with a graphical user interface this is sometimes accomplished
by clicking on an icon. Mathematica comes up with the prompt In [1] := and
awaits an input which is terminated by RETURN. The notebook version of
Matnematzca IS Just Slightly ditterent m that commands are sent Indlvlduauy
or in groups with SHIFT-RETURN. Mathematica is an interpreter language
that processes input immediately and presents the result on the screen in the
form Out [0 0] = .... In doing this, all expressions which were defined earlier
in t.hp ~~.mp
. arp .1 int.o ., Onp pnr1~ ~. J I .. .LL .L.
-
YV 1.111.1. ~.U
......
&
.1 ...
r:L.I.
..L 1 .
In [1] := 4 + 7
Out[1]= 11
InL2J:- 3 4.2 space = mUltzpll,catzon
Out [2]= 1206
In [3] := 2*3*4 * = multiplication too
Outf37= 24
in L4J : - :;& II Ii' I - al,Vl,sl,on
Out [4]= 3
Tn r.':;1 0 2"-:t "
.
-
DutL5J- 8
In [6] := (3+4) "2-2 (3+1)
-.. Ai
-n.. +- .f1:1-
In [7] := %/5 %= the most recent result disvlaued
212 A. First Steps with Mathematica
41
UutLIJ= -;-
OJ
n, rof "'"1_ 0
In [17] := ?Log
Log[z] gives the natural Logarithm of z (logarithm to
base E). Log[b. z] gives the logarithm to base b.
In[17]:= Log[E, %15] %15 is the same as Out [15]. All In En]
and Out En] generated during a session
"n .... hD
- -"~ JIn
-- -- nnn .....
~
In the following we will omit the input and output designators In [ .. ] and
,
Show [ .. ] displays graphics objects with the selected options.
214 A. First Steps with Mathematica
A
ParametricPlot3D[{r Cos[t],r Sin[t],r 2},
n =
N [n] ---t 2.4329 10 18 , the variable n has the value 20!
e-
C = (a+b) A3 ---t
3
A
f[x_]:= Exp[-0.2S x 2] Cos[4.S x] This is how functions are de-
fined. x_ zs a "place holder" with the name x. The underscore character in
OJ x one can use any omer variame name nere as weu. une oowins me same
result with the commandPlot[f[t] ,{t,-Pi,Pi}] .
fermi re_.b_l := l/CExnrbCe-lll +ll A function of two variahle.~.
Plot[{fermi[e,lO], fermi [e,Xnfinity]}, {e,O,1.7}] Plot of
two Fermi functions. Infinity = +00 .
.......
'TIL
~
n- 1.
ov'Vu 'V'V .- ..J
........u
- &
1 .1 L
UJ a..<" &
1
.
a = Random[]
The right side is evaluated and the resulting random number is assigned
+,." +l,." ..."' ...; '" 1-..1" _.
_ ...., 'V"J .. t'
+,." _ ..n;l1 ...;,,1..:1 +l,.;" ~ .........1-.."..
u'V U'V ~ u'V _ .,. J 'V..... uu
r:= Random[]
The right side is not evaluated at first, only after the variable r is
referred to again. The right side is reevaluated each time r is referred
to. Each time a new random number is oroduced.
Lists
numlist = {2,3,4} A list with three numbers. Lists are written in curly
braces {} .
- .. r_ _'1
-.
.: .... , --I. r ..
----.
,",,+
~~~
'1":'1
::J
..
., ",,'" "
'V~_ ~ J.
..J ....._ , .. '""+
_
,;",,,
v_
1';",1-
vv_
~
.. .
.&.;;1".-.- .. . .. .L\X,
,. .LXJ."I ' ,. -
\X,.,.,u.U;;JIJ, . - --".
216 A. First Steps with M athematica
1I1S'C~J.O'CLJ.1S'CJ
-
L15'tl'".lo't L J ptOtS (UStS OJ) aaw.
letters = Table[FromCharacterCode[j], {j,122,97,-1}]
--+ {z,y,x,w, ... }
Sortlettersl --+ ~a.b.c.d.... 1. Sort r.. 1 sorts not onl'll letters
v ... .,
~ln~
J..n .I- .....vV' J.
v.
letters [ [3] ] --+ x, the third element of the list letters. Parts of
lists or of expressions are designated by double square brackets [[ .. ]] .
. . . . . . . "
lIeng'CDLJ.1S'CJ ----? 'U, we tengtn OJ we USt .l15't .
list [ [20] ] --+ {2.95, 1.91077}
J.1St [[::lO, J.)) --+ :l.~b
data =
Table[{x, [x]+r}, {x,-1.S,1.5,0.OS}] II Chop
Noisy data. Chop replaces real numbers which deviate from 0 by less than
10- 10 with O.
p:l = L1stPJ.ot[data)
Show[pl,p2] Show[. .] can combine graphics objects.
A. First Steps with Mathematica 217
!!list..dat.
zs comman
dat.a2 == dat.a ~ True. == is the logical equality operator.
OUt.put.Fo~ T measure at.
! !measured. dat measured. dat could be a data file that was generated
in an experiment.
model [x-l =a A
+ b x + c x 2 + d x 3 + e x 4
A A
We define a
model function whose arameters we want to fit.
Needs [Statist.ics'NonlinearFit' l zs comman
package NonlinearFit.m .
uses the fact that, for n > 0, the first zero of In(x) lies approximately at
n + 1.9n1 / 3 and that the following zeros are all separated by about 7r.
'L
! 1 '7.~rn n r lr 1 .=
Block[{f,start,rule,zero,list},
f [x..] = BesselJ[n,x];
start = Ifrn==O 2.5 n + 1. 9 n""(1/3)1'
"
oL .... ~'W ..
1:'': -,n
-
f.t: f '
"oL ...... ."
_.n
v, l( .... ' ..............11
J.",
zero = x I. rule; list = {zero};
While[Length[list] < k,
rr
---- ----LL ........ . -,
-.... , 0; .. + _1 1 1 ..L no;
..... r
rUl.e = r1naI\OOl;;LILXJ--V,tX,Sl;;arl;;JJ;
zero = x I. rule;
AppendTo[list,zero] ];
If[n> 0, PrependTo[list,O]];
Plot[f[x]J~x,O,list[[-l]]+l~];
list ]
-m
~~
- -
'L
" r":t 41 --4 PInt nf . T.' . thp ..fir.flt ..fn'll.r 7.prn.fI nf..
.T.,-,( , and a IiJlt nf
J3 (x) .
T ........ ,1 ,.~
'I;
-~.- -"
Do[Print[R Hello World Rl,{20}l ~ Writes Hello World to the
screen ~u umes.
A. First Steps with Mathematica 219
T.nnnQ
. -
Do [expr, {iterator}]
.
...... .. .L----'
For [start, test, 1ncr, body]
... 'L ..!I.
_.I
_.
... -
""'..
n .....
, ""'.. - . .. n
, ,4
...... .J ...0
...,.... ." ..., ... ~",
.1.
"'.Y~'
Do[Print[sl,FramCharacterCode[j],s2,j],{j,65,75}]
Writes the first 11 capital letters and their ASCII codes to the screen.
For [1=J., 1 < J.J., 1++, Pr1nt[1," II
,1 ;all ~ lienerates
the numbers from 1 to 10 and their squares.
... .= I . = - r 1 ~ n A.\
-- .
..
~ n".,
tAnll'; , .. r'"
value 1.5.
NestList[Sin, 1.5, 30] NestList [ .. ] yields a list of all values cal-
thp thp .
I I .j"., n(
- .
f[x_]:= N[Cos[x],18] numerical value of cos x to 18 digits.
FixedPoint[f,1/10] 0.739085133215160642, the fixed point of
\.-U;:);L,
II
li.e;., ",.e;;L JUI
I' I' ,
\.-U;:);L
~
.
;L c,u
rr
~l.IIJJ
.
......... l.II, ...... y.
Simplify [D [%, x] ] ---+ the integrand of the above integral. The function
Simplify [ .. ] reduces fractions to their least common denominator and tries
to put the result into the simplest possible form.
---+ t e e nzte zntegra 0 e
- r ..... '
L-" r ............
T. 1. 1.
... "oJ ., ".., ......
T.
..
r'L ,
LLlJ
yieLas me transpose OJ D
l;araano formUla.
nb = N[b] --+ the numerical approximation of the matrix b . The exact
.J .1.
nrp ... . J
~ h'l' oJ
..1
J .1. 'I1l9.th nn
.,
nf 10- 16
"
'III';
.- r,.,'h 1 ~ [() A7f\11Fi.
- ., "Aa
- l
() 04()Q()4Q , () ()()I'\L!A,.,. ... ')l
~
n J,j "f
Solving Equations
.....
60
...!!II- .&. 'I ...
L ...... g --
_...
......g ,
r.
1.-' _VfJ
.ft. 1 J:!.
u.uuo
..J. . .1 1
.
Solve [eqns, vars] tries to find exact solutions.
NSolve[eqns, vars] numerical solutions of algebraic equations.
'I' .I
. --- -..--, -.... ,..
- ,, ___ r_
'"'
1
...... '"
......,.. 'V... " ....'V "'J "''''V''''''''''''
,..~
.. -.......- ....
l..
Remove L"GJ.ODaJ. * . j
~1St - t~, ;&, :l:la), golD), x D, :l:LDJ, :J.", 51nLPJ ;&}
PositioD[list, f [_] ] ~ {{3}, {6}}, a list of all positions with
fr . ,1 . "
~ ~
yzetas ne vame True. 1 nere are more nan .:)U Juncnons OJ ne Jorm *l.I wztn
which one can pose questions.
? *0 ~ all these functions.
l'ne exclamatzon poznt l!) zs the togzcal negatzon. l'he constructf,on expr L# J &
turns expr into an operator, a so-called pure function. # is replaced by the
argument.
- - ..:I
' ......
r , . r.L r: ..L
..,."".
~'Gdby~
CN' ~
~
CP ;:,-
~
.)0~
L
B. First Steps with C
ondly, one often has to use memory addresses, and e does not control whether
indices accidentally exceed the previously defined range. Beginners in partic-
care;
float f, rational_number;
long long_i;
double Ion _f
ing int, char, and long are integers; those following float and double are
rational numbers. The different types correspond to different accuracies and
an ASCII character) is reserved for char, two bytes for int, and four bytes
for long.
226 B. First Steps with C
_ .... f t ( )
.
.r
int i;
fore i=4; i<16; i=i+l) printf(lIi=1.d \n",i);
~
'<J
uraH !llQ
1
tho ,.
1
Lilt::
,. ..
fn.. tho
A~AA~" A A A O
. ,.
. 1.1 ..
.
tn ha
'<J
A
.
-l
%d int
%ld long
%c char
%f float (ftoatine:-noint renresentation)
II _
,..., -,=1_ ... + t. ~n 1
. .)
\' .& '.& 'J
%If double
%s string
rn.
~ lIt:: ~J AAA~~A
1 .
\11 11::1 a
. ,.
\,;Ua.1 avlJ'I:'~ LuaL
"
a
.. ,.
uut:: It::t::U. J.L \,;UI
Y.
.&
to the RETURN key.
, ,.
uy LUt::
.
A
,. . \, "J.
1 .
The formatting instructions above can also be used for reading, which is
. , "
wa.... .u. \ I
{ double i = 0.;
fore; i<100.;)
{ printf( "Please enter a number \n");
scanf{ "1.1f ll , I:i);
printf ( "You have entered 1.1f", i) ;
}
}
... .. .
ThiQ
.
.&'
1.1
~
1.
,-,au IJ'I:'
. .1,' -l
Q(lTllP
,1-
alJ IJII'I:'
.&
i:)all~'I:' IJIIII'I:'. M.
n
. 1 Tn t.hp t.vnp
T"'"
or 'J
. .. "
..
.&
-l
-l
auu
t.hp
instructions can be used in the for loop. 3. If one passes a variable, here i,
B. First Steps with C 227
vector.
main 0
str[99] the last character. str is the address of the vector (= the address
of the first element, or &str [O])j therefore it is sufficient to pass the name
. .
,
marked with the ASCII character \0 (= null). printf prints all characters
up to the character \0.
#include <math.h>
II
in the header files math.h, stdlib.h, graphics.h, time.h, etc. The line
#def ine N 1000 causes the symbol N to be replaced by the symbol 1000
sum = a+b;
a = b = alb * e;
mod = a 1. bi
228 B. First Steps with C
,
Logical operators combine logical values and produce 1 (true) or 0 (false).
,
have to be present, and multiple commands have to be grouped into a block
{ ... }, as shown in the second example.
case'e' : exit(O);
case'f' : scanf("y'lf".&:a); break;
case's' : scanf("y's".str); break;
instructions can be
,
variable ch, and then the case instruction that contains the corresponding
B. First Steps with C 229
This command causes the program to jump to the end of the switch block
{ ... }.
for (sum=O. i=O i<N i++) sum +=arra [i] for()
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
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)
fmod(x,y) Remainder of x / y
These mathematical functions return a value of type double. They have to
be declared beforehand with #include <math.h>. If the ar ment is not of
double r;
r = rand() / (RAND_MAX +1.);
#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;
wnn tne type aeCIaratlOns lOr tne IUnCtlOn as weu as lOr tne arguments. .1 ne
commands of the function f (x) are enclosed in braces { ... }, and the value
of the argument of the return statement is returned when execution of the
function completes. If no value is returned or no argument is passed, then the
type void is used. Only the value of the arJ?:ument x is passed, so f cannot
change the value of the variable x here. If, on the other hand, ix, the address
of x, is passed, then f can also change the value of x:
-
it,
. .. . ..11'
main\J
1.
double f(double *),x=O.;
while (x<100.) printf (II \n f (l.lf)=l.lf" ,x,f (&x ;
}
, . .
printf(" \n 1.1f \n",Sca1arProduct(u,v,n;
}
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
Variables can only be used within the function in which they are defined.
If they are to be valid in more than one function, then they have to be
declared before those functions outside of an curl braces. u v n i and
ScalarProduct can thus be used in all functions (and will have the same val-
ues everywhere); sum, on the other hand, can only be used in ScalarProduct.
void si nifies that no variables are assed. Of course now the function can-
B. First Steps with C 233
.A . . rJ1-~~~'
...........t'''''
if (a=b) dosomething 0 ;
'T'l...~
.a. ........ r .......... 1
'-'
.4- 4-
uv uJ P"" u.
.1. 'T'1
- u. .a. ........
v
,.1
~~~.~
.1-
'-'
o to tne vanaDle a ana tnen tests wnetner tne valUe OI a IS equal to zero. 11
not, the function dosomething () is called.
integer = 3 * rand () / RAND MAX'
All ..........;<:\hlt:>'1 ~nr1 ~rt:> to. ht:> o.f t.unt:> ; .........._ C'
-" . -
1 I'ATYl_
-<;J
pilers evaluate this expression from right to left. In this case, the quotient
and with it the entire expression receives the value zero, since the remainder
i~ lo~t. in t.h p of t.wo Tl
1"
,. onp
" " tht:> _1 _1...] a1 _1
v &
1-
.. _1
..J 1 '-' L 1 11
L1 1"\ 1 ...] ()
I- J..l.l & "V ".... ~ v, .... , u..... u ~ .. -0
Vectors of length N have indices between i=O and i=N-1; thus the last com-
mand of the for loop, vector [10] =100; ,assigns the value 100 to the mem-
ory location after the vector without any warning, and the programmer does
not know what is being overwritten!
main 0
{
,.h~,.. *n~m ...
~_":_+4' (IIt.n.~+ . : _ ......__ ~ __
r
................~..
\
,
II"/ II -
,... , "'QUi'"
J
.'\
I
--
?
- - - "
11\.
, ,
}
the character strIng, out the aaaress 01 the vector msg may not oe changea.
The following program eliminates both of the above errors
maine)
.(
char name[20],*msg;
printf(" \n What is your name? II);
scanf ("1.s" ,name) ;
1Il~6-
... ~ ~ .. t
_1
G.l1U
\,..
\V.
IT'l_
~L.n:::;
l
-A-
. .L., ~
Q
.
~
_1- A-
LLLQI. QL 1I't:'1.
int a=100;
scanf("1.d",a);
scanf mterprets a as the memory address numOer IUU and overWrItes What-
ever was there. The correct read command is scanf ("y'd II ,&a) ; .
T ..L
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 (*).
passwor, . ese are 0 alne rom e sys em manager. or every user ere
is a separate home directory on the hard disk, on which one's own programs
can be stored.
After entering the user name and password, you will find yourself either in
a shell- i.e. the com uter waits for commands - or a ra hical user interface
(usually XII) is started. In the latter case, if a window is not automatically
opened, one has to generate a window using the mouse. Then Unix commands
can be entered in the window and terminated with RETURN. Windows can
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.
.c.
c C source code
Help
man -k keyword to obtain a list of the commands which contain the word
keyword in their one-line description.
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
!
password is yppasswd.
outputs by inserting the characters < and > respectively. The output of a
C. First Steps with Unix 239
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)
executable program.
The C compiler which comes with a Unix system is called cc. With the
path
-Ix The linker links the library Iibx to the program
is
c. First Steps with Unix 241
Networks
IS sec IOn we WI
network.
Every computer connected to the Internet has an address. This address
consists of four numbers, each of which can vary between 0 and 255. Every ad-
dress has a name associated with it. ft . h sik. uni-wuerzbur . de for ex-
ample, currently has the address 132.187.40.15. The individual groups of num-
bers cannot be mapped to the components of the name in a unique way. For
exam Ie an address at the Universit of Wiirzbur . uni-wuerzbur . de
onnectIons to
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.
or hersell; the computer asks tor username and password. Alter a successful
login the following commands can be used, among others:
sP.ts thp. to to Lp.. t.hp n~.t.~. ~.rp to ,
hi .:I 1..
~
_.:~"I.. ~ 4-
.' '
~
mput files similar to put, but this command accepts wildcard characters
in the file name and transfers multiple files
.. -.LranSler
.lnt;ernet; -~ ue
~
-
Many institutions offer programs which anyone may copy freely. These can be
obtained through the Internet, using FTP. To this end, special FTP servers
~ . A
,
\ l;Ullt:l.lL .I.e
TT'1o ,,
.. nn .. n ... ~n ..... ,
.I."~ .I.0'
.<j;V .I.tJj 11.1 Ll.lt:
"
,.
.y /
I I .
PUU/ ~t'~.1~.
Data Compression
'T'l...~~
.&. ,u",&&,
~~
&&& ~.&
,
.... "'.&
4-~
U~
~~
UU/
,~ -1:~1
'" ....&U&'- & , . ~-~
U/& ' "
,~ ..] A.
uu"'..... '-' &&'"
'*\ '.I.'
yA 'U'
rrequently usea program is callea gZ1p' '.lne commana gZ1p I11e com-
presses the file file. The output file has the name file. gz. To decompress,
one can use either the command gzip -d file. gz or gunzip file. gz.
display its windows on the XII-capable monitor of our local computer local.
First of all, we have to tell our computer to accept displays from the other
VUC.
rn1. . .1
.L 1.11., I., UVUC v 10,
.'L
A..LLViCI" ~
A, ,1..
ogWV "og. '-'II "IIC ~ ogWV "og
1..
W'V Ilo,V'V "V
-r
set the enVIronment vanable DISPLAY. tloth In csh and m tcSh thIS IS done
via setenv DISPLAY local: o. The symbol: 0 represents the first X session.
All X programs called from now on will send their graphics output to the
monitor ot local.
Literature
"'1', . .
. a..,
T.l" T'lo' -, C (1(\(\A\ Tl..n TT... :.r r\ C'l TTT'
l\T.nn.
~
_.IorK .& '-'. \,&,"''''.&1 ....u ' V " ' & & &. . .
..- ~ '-'J ~U'VA& &&'VJ' 'V
L
~'Gdby~
CN' ~
~
CP ;:,-
~
.)0~
L
D. First Steps with Xgraphics
,
library of the X-Windows system, and provides simple commands for man-
aging windows and drawing in them. The many parameters which have to be
done as follows:
ftp ftp.physik.uni-vuerzburg.de
e username:
ftp
#include "Igraphics.h"
#defineMAII 640
main 0
InitIO;
mywindow=CreateWindow(MAII.MAIY."random walk");
ShowWindow(mywindow);
case 2: y++;break;
case 3: y--;break; }
}
per e w m v
and the file has to be made executable via chmod u+x compile. The result
should be the picture shown in Fig. D.1. Then if one enters any character in
Isa ears.
Additional demonstration programs, which also show the other capabili-
ties of Xgraphics, can be found on the enclosed CD-ROM.
glewood Cliffs, NJ
248 D. First Steps with Xgraphics
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/
sum=O. ;
Do[sum=sum+data[[i]].{i.length}];
average=sum/length
]
avera e [data ] : =A I [Plus data] /Len th [data]
250 E. Program Listings
"'.... orn ~
#include <stdlib.h>
#include <time.h>
ma1.nu
'l
float average(float *,int)j
int i;
clock t start.end:
ofl n::.'t: ...1_ ... ___ .... r1 nnnn, .
,.1 ') .
for (i=O;i<10000ji++) dataset[i]=random(1000)/1000.j
start=clock 0 j
for(i=O:i<100:i++) avera~e(dataset.10000):
nrintf( II average = Y.f\n" average (dataset 10000)) .
- -
end=clock 0 j
printf( II time= Y.f sec 1I,(end-start)/CLK_TCK);
,
getchO j
J
.......... .. . .. ..
..........
... ~ ....T l'
. ...- ..........
sinuspsi[t_,phiO_]=JacobiSN[t,Sin[phiO/2]-2]
phinorm[x_,phiO_]=2 ArcSin[Sin[phiO/2]*
C!;
.. . rv Tr,., ;nl ....h;nll/....h;n
~- ~c .~ c
'C .~~
"
f[t_]=(Sign[1-t]+Sign[1+t])/2
fs[w_] = Integrate[Exp[I*w*t], it, -1, 1}]/T II ComplexExpand
T=10
Show[gl,g2, )
252 E. Program Listings
{s,64}]//N
plot4:=Plot[{Re[fapp1[t]],f[t]},{t,-5,5}]
fapp2[t_]=Sum[N[fslist[[s]]*
+
onJugate
Exp[-2 Pi
lot5:=Plot[{Re[fa 2 t
, ,
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]
plot4:=p4=Plot[BesseIJ[1,x],{x,0,10},PlotStyle ->Thickness[0.001]]
plot5:= (If[Head[p1]==Symbol,plot1];If[Head[p3]==Symbol,plot3];
- ."_-.TT.
~ ':. _ _..
r. -" r.
L.... &. t ...... t " t . " , \oJ,
&. &.~ I
I A
."
_ - ~'i.l."
square[{t_ty_}]=(y-f[t])-2/sigma2
chi2=Apply[Plus t Map[square t data]]
find:=FindMinimum[chi2t{atO.9}t{omt1.1}t{phitO.1}t{bt.2}]
fit:=If[$VersionNumber>=3. t
BestFitParameters I. NonlinearRegress[datatf[t]ttt
{{a t 1.1}t{om t 1.1}t{phi t .1}t{b t .2}}t
ShowProgress->True]t
N"... 1 . ... i ... rit ....... .,r... 1 ...
II_ 1 11. I __ 1 ;1. .f_l.": ,,1.1.
t,";..- t . 11. t .fl..
:''L.. -t:. .. , t'
-~t t ... -t -.: -~ -~ .~ ~
pvalue[x_]=1.-CDF[ChiSquareDistribution[7]t x]
interval={Quantile[ChiSquareDistribution[7]t. 05]t
Quantile[ChiSquareDistribution[7]t.95]}
limlx_J=QuantilelChiSquareDistributionl4Jt xJ
plot2:=Plot[PDF[ChiSquareDistribution[7] tX] t{x t Ot 20}]
rule = If[$VersionNumber>=3. t
... ..... - I I _ 1
I
11. I __
N"... 1
1 11.
ft
I_l.':
rit ....... ., r... 1 ...
11. - Il.. ':'1.~' -
.
-.T ...
~r .. '
t"'L"oJt"t
~ ......
....- t - .
t ..--t -. t "r- t . t ..- t .. .. t
..... r .... ~
-~ -~ -~ ~ ~
g[t_]= f[t]/.rule I
step:=(data2=N[Table[{ttg[t] + .4 Random[]-.2}t
~1: n ~P; ~ p;lll
T-f: _.
r~"
- =~ .
-
____ A
~.
__ ________
-
I
_.
r..I
t-4=r..,
.. -.. t .. t
1.1 __ ''':
" ~."
{{ataO}t{omtomO}t{phitphiO}t{btbO}}]t
NonlinearFit[data2 t f[t]ttt
{{ataO}t{omtomO}t{phitphiO}t{btbO}}]] )
tab:= tab = Tab.leLtch12tatbtOmtph1J"!.stepttlUUJ"J
abtab := MaplTakel#t{2 t 3}J"ttab]
plot5:= ListPlot[abtab t PlotRange->{{.4 t l.2}t{-O.045 t .2}}t
AspectRatio -> 1 t Frame -> True t
FrameLabel ->{"a" "b"l Axes -> None
AlA _> Pn;"''''~;''ArO
~
Pl 01511
"
254 E. Program Listings
.. D
..... v
'1\ Jr. . . .
...
.. ..,
-.:-
. .. .. .- ...
.1 _
..........
'r"-
r. r.
.~
..,
L ... - ....J
. J'
....
.~
r,..
'J
Aft A''''
.J-.-~v.vu.v.T.T.J .1. ....
r .... , ..
V.T.J ..
p4=Graphics[{Thickness[0.001].
Table[Circle[Drop[r[i]. -1]. 0.1]. {i .10}]}]
SetOptions[ListPlot.Frame->True]
SetOptions[Plot.Frame->True.RotateLabel->True]
plot1:=Show[p1. p2. p3. p4. Frame ->True.
AspectRatio -> Automatic.
PlotRange -> {{-2. 2}. {-2. 2}}.
_'L .... 1 _,- Illy"-II .. II "\.1 9
oJ ~
J~
.. r
U.l.D"L.I.-_.D_"I-~''''
.. - r, ., ,
0 ' . , ... O'.J."
pot[rh_]:=Sum[ l/dist[rh.r[i]]-l/dist[rh.r[i+S]] .{i.S}]
plot2:=Plot3D[pot[{X.Y.0}] .{x.-2.2}.{y.-2.2},
AxesLabel->{l x l,l y ","Phi"},
PlotRange -> {-S,S}.
PlotPoints->40]
~
-
,... .................'r, -~ -~
'J --.o;rT 'T "'-'T
Needs["Graphics"PlotField II]
efield=-{D[pot[{x,y.O}],x],D[pot[{x,y.O}],y]}
direct ion=ef ield/magnitude [efield]
n1nT~=P1 ....1i1ril; '1 on ..(x 10 10)...fv -10 10).
P1 ....
~
-~~nl
E. Program Listings 255
1.
va ua e r , ,
DisplayFunction->Identity]
p2:=ParametricPlot3D[Evaluate[r2],{t,O,1},
Dis layFunction->Identit ]
3:=ParametricPlot3D[Evaluate[r3] {t
D's la Funct'o ->
1}
D[fy,x]-D[fx,y] }
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.},
.
P1ot[{pmax[v],p[v]},{v,O.34,5.},
,
P1otRange-){{O,5},{O,2}},
Frame -) True, FrameLabe1 -) {II V I l , II p ll} ]]]
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 ]
P10tRange -) All,
FrameLabe1 -) {"l/n",IIEO(n)"},
P1otSty1e -) PointSize[O.02],
Disp1ayFunction -) dentity
gr2 = Graphics[{Thickness[O.OOl],
Line[{{1/20,O.559146327},
{1/7 ,O.559146327}}]}]i
. " , , ,-
ev2[k_]:=Tab1e[{ev1ist[[i,1]],ev1ist[[i,2,k]]},
{i,Length[ev1ist]}]
p1ot3:= ( Tab1e[gr[k]=ListP1ot[ev2[k],P1otJoined ->True,
1SP ay unct10n -) ent1ty,
Frame -) True,
FrameLabe1 -) {1I1ambda","energyll}.
FrameTicks -) {Automatic,
*"
Disp1ayFunction -) $Disp1ayFunction] )
E. Program Listings 257
p 0 0 va ua e s 1S , omega,
PlotRange-> 0,1 , Frame -> True,
FrameLabel -> {"omega","Abs[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},
so
.-
~ -'::1._ _.. . .r.r
.... i t\t\t\t\
' -,-
-
' ...
l-
Automatic},
FrameLabel ->{lIomega","P/PO"}]
-
~.'l
_. .
n!:UT1l
-- ...
V.au.a
. .. . III
L
mat2/.{f -> 1., ml -> 0.4, m2 -> 1.0, q-> x}]]},
{x,-Pi,Pi,Pi/50}]
lotlist=N[Flatten[Table[
Ma[{# [[1]] ,Sart [#[ [2,k]]] }It,
eivenlistl.{k.4}] 1]]
plotl := ListPlot[plotlist,FrameLabel -> {"q",lIomega"},
Frame -> True,Axes -> None,
FrameTicks ->{{{-Pi,"-Pi"},{-Pi/2,"-Pi/2"},
r,..
l.V,
",.."" rn."'" lin.' , ... "" rn.' lin..: ",,- "-
v J , V . , ... , . . . ,... J , \''' . , . . . J J ,
, ." '\
- ..-oJ
mainU
{
int gcd( int , int);
int ie, n, nold, m, p, q, x;
1'1,.... },.1 ... "l.;onUl
- ... -
n;
.- a nl::.;n1t'1
.-
.
nl::.;
& .nl::.; ... av
.:_ ...
.&&U
_..1_':
0 ...... - ' ...
-
~
initgraph(ltgdriver,ltgmode,"\\tc")i
settextstyJ.eU,U,l.);se'tcoJ.orlIU:;U);
outtextxy{SHIFT+l00 ,::>HJ.l'--1'+QMAX+l0, "Hors'tad'ter tiu't'terrJ.y') i
settextstyle(O,O,l)jsetcolor(WHITE);
outtextxy(SHIFT+l00,SHIFT+QMAX+60,"Commands: eXit,arbitrary");
E. Program Listings 259
clearvievport();
outtextxy(1.10.str);
setvievport(SHIFT.SHIFT,SHIFT+QMAX,SHIFT+QMAX,1);
C.~I
~ . . . . . . . . y~ - ( 'l
. ...
~ "
, (~ ..
,,~ ...
.\
., .... \ .... ..
r
~ _
.
... ~ .. ,.1~
...... , r , . v.v,
-
40-
nold = n;
260 E. Program Listings
., "1_._
1..
,I ... -- ---r
': __ 1
/* p-loop */
};
if (kbhitO) {str[O]=getch();getch();if(str[O]=='e') break;}
l' 1* q-J.oop *1
closegraph();
} /* main */
.r.
if( b==O) return a;
return gcd(b,a%b);
}
{k,-Floor[(spindovn-1)/2],Floor[spindovn/2]}])
Print [II II]
Print[1l The ground state energy for U = 0 is: II , tkin]
.le:It = t'ermutat1onsl TaD.lel l.:IL J <= sp1nup, 1, UJ,
tj,sitesJJ J
right = Permutations[ Table[ If[ j <= spindovn, 1, 0],
{j,sites}] ]
index = Flatten[ Table[ {left[[i]],right[[j]]},
.fi .T, ... rlAf1:1l f;T, ... rT;rJ'h1:1l 1 11
.....,.-1 = T .. r ..
.'L
., .
.'L
...
... "1
plus [k_,sigma_] [arg_]:= ReplacePart[arg,l,{sigma,k}]
minus [k_,sigma_] [arg_]:= ReplacePart[arg,O,{sigma,k}]
sign [k_,sigma_, arg_] := (-1)-(spinup*(sigma-1*
~-1) ~::iuml argLLs1gma,JJJ,'tJ,.lt-l1'J)
cdagger[sites+1,sigma_] Lany_J : = cdagger [1 , sigma] [any]
c[sites+1,sigma_] [any_] := c[1,sigma] [any]
cdagger[k_,sigma_] [0]:= 0
c[k_,sigma_] [0]:= 0
.. ...... r'k' ~; O'm::\ 1 r'" ~ r::\TrJ' 11=
...-
4l, ( 1 _ ......,... r r... .; ......... 1.. 1 1 ,
'O~ ...
-, -
,
scalarproduct[z[arg1_],factor_. z[arg2_]]:=
factor* If[arg1==arg2,1,O]
H[vector_] = Expand[
-t*Sum[cda er[k,si a] [c[k+1,si a] [vector]] +
cdagger[k+1,sigma][c[k,sigma][vector]] ,
{k,sites},{sigma,2} ] +
u*Sum[n[k,1][n[k,2][vector]] ,{k,sites}] ]
II
,
II X II ,end,". II]
h = { hlist = Table[H[z[index[[j]]]], {j, end}];
Table[ scalarproduct[ z[index[[i]]], hlist[[j]] ],
i,end, j,end])
menu
enerate!"
u
r~r ......1
~. ~. , "~ ,~. .,
f .... n s::: s:::')1.11. f n
"I ~ 1 .~. , , ~ ,. ')1.1
-" .. ,
..... v ........................" ,
main()
{
void channel{double);
int gdriver=DETECT,gmode;
char ch,str[100];
double xit=0.4,rmin=.88,r;
int x,y=50,i.ir;
............
..: ...: , 11\ \ 'V_
II. . ...lI_": .... _
... '-0-- .... --, ....-
-
... II'" .
4. ....
maxx=getmaxx();
maxy=getmaxy();
setcolor(RED);
settextstyle{1.0,1);
outtextxy(100,maxy-80,1I Lop:istic map x=4*r*x*(1-x)II);
settextstyle(O,O,1);setcolor(WHITE);
outtextxy(50.maxy-30,
II Commands: lower,higher,refresh,print r,channel,arb.,exit II) ;
"' ..+u;
- _.
_ .. 1
,_.
(1 1 """"vv "",,"vu_1nn i ) .
. /1 _ _ ..: _, ..... / / ___ _1 ;"1\,
. .
J' '--J ---"
while(1)
{
X1t=4.*r*x1t*\1.-x1t);
x=xit*maxx;
putpixel(x,y,WHITE);
if(kbhitO)
E. Program Listings 263
r
_ . ...: 1. ( -'- ( \ \
- - - - - '0' " ,
{
case ' l' : if (ymaxy-100 y+=1;break;
case ' h' : if(y>1) y-=1;break;
default : getch {) ; break;
case ' e' : closegraph 0 ; exit(1);
case ' c' : channel(r);break;
case 'p' : sprintf(str,1I r= Y.lfll,r);
'(1 ,v
w
str)'
'h"''''J:lllr..
' .... , . ... ,~ ....... .,~
..... "''''' -(" \ ,.'- , . .1
} /* switch */
r=1.-(1.-rmin)*y/(maxy-100);
for(i=0;i<100;i++) xit=4.*r*xit*(1.-xit);
1 I . 1r *1
Jo/* wh11e *1
}/* main */
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;
}
""--
{Thickness[0.002],GrayLevel[.6]},
.
n .. C!h; ...... rrn nn':l n nn':ll.ll.
-~-- .
{Thickness[0.002],GrayLevel[0]}},
FrameLabel -> {II XII , II f [f [f [f [x] ] ] ] II} ]
nr lX_ , r _J =N lr lXJ J
11stlLr_,n_J:=NestListLnfL#,rJ&,.65,nJ
plot2:= (list=list1[.87,40];
264 E. Program Listings
... _... ,W'" ~ r, . W'"
- ..-
W" .... r", "'''',
0' ,,,..- ... v" L...... ~"'..- ... v" .. ,,] ......
. .
"
-" h.y
.J;
'LV. V-'.J ,
. "
g2=ListPlot[list,PlotJoined->True,
PlotStyle -> {Thickness[O.OO2),GrayLevel[.7)},
FrameLabel -> {t1n",t1 x (n)"},
DisplayFunction -> Identity);
Shov[g2, g1, Frame -> True,
DisplayFunction -> $DisplayFunction) )
.r. .l"'... '::tr....
_. - n "'.... "1.1 .=(...1=Pl",... r... ~r,..
-- ...1 rv n 1'\.
... _. ,. .... ,T .....,. ,
.;..~--, -' '. '- -' - .,
.+
..
AA' -~.... ~"
r, ~ r:' . ; oIL
LU.L L1I',.L.J"', V.
'"
oJ, oJvV.J ,
..... "'''',
'VJJ'
lil=NestList[{nf[#[[1]),r],nf[#[[2]],r]}l,
{xx,nf[xx,r)},1000);
li2 = Flatten[Map[{{#[[1]],#[[2]]},
{#[[2)),#[[2))}}l,lil),1);
li3=Flatten[Map[{{#[(1)),#[[2)]}}l,li1],1];
g2=ListPlot[li3,PlotRange -> {{O,1},{O,1}},
PlotStyle -> PointSize[O.015],
n;"'.....l .... .;",... _'> T,'" 1 ,
_':J_T ..:
0
_+n,_ _
"'+v r, . : '1" n,"
.. _ _ _ , .
.... , . .
__ ...
... .... - -. ..- -....
_.... .r.rn 11. .r~" 1 ~ ~
, , , ,
..... v
.-
, "', ...........
,
PlotStyle -> Thickness[O),
DisplayFunction -> Identity ) ;
g4=Graphics [Text [
StringJoin[t1r = ",ToString[r]],{O.5,O.05})];
g5=Graphics[Line[{{O,O},{1,1}}]);
Shov[g1,g2,g3,g4,g5,PlotRange -> {{O,1},{O,1}},
AspectRatio -> Automatic,
... -'> T....,.... .
n..: __, _ ... _.... cl.>n..: ._, _ ...
. "
'",-
. "
.1\
,
h[x_)=97/25 x(1-x)
hl[n_]:=NestList[h,N[1/3),n]
hl[n_,prec_]:=NestList[h,N[1/3,prec),n)
tab:=TableLtprec,PrecisionLLastLhlL100,precJJJ},
{prec, 16, 10O})
plot4:=ListPlot[tab, Frame -> True,
PlotStyle -> PointSize[O.01),
-.r"D__
",h... l -'>
.. - "~_~,,,_ ",-4'
._-___ ,_ , .......
.- ......+1. __ "
,
II.
.:/
~
" ............................. ., "" .I J
period[1)={c,1}
accuracy=30
mUl.t=30
period[n_]:=period[n]=Join[period[n-1],
correct [period [n-l)))
correct[list_):=Block[{sum=O,li=list,l=Length[list)},
Dorsum+=lirHll ..fi2 .Ill
Ti'rnrltUH... .,ml H rr1l1=o . 1; rr1l1~1l
,- .- '- .
g[n_,mu_):=Block[{x=Sqrt[mu),l=Length[period[n))},
--
1 .. 1
E. Program Listings 265
int gdriver=DETECT,gmode;
int xs,ys,color=WHITE,maxx,maxy;
long nsum=O;
double k=1.,sig=.4,p=O.5,x=O.55,pi=M_PI,xnev,pnev,h=O.,vind=O.,
xold,pold;
char ch,str[1000];
initgraph(lgdriver,lgmode,"\\tc");
- -
O'
,f\. ,
'\
~"""'J6-V~"""'J'"
settextstyle(1,O,1);setcolor(RED);
outtextxy(150,maxy-80,"Frenkel-Kontorova Model");
settextstyle(O,O,1);setcolor(WHITE);
outtextxy(100,maxy-35,
"Commands: exit, print, nev start, clear, arbitrary");
xold=x; pold=p;
vhile(1)
{
n..... u=n~1r/') In;*",; ... (') *n;*v\' .
_.0__ -r.o--.._,
xs=fmod(xnev+100000.,1.)*maxx+1;
ys=(1.-fmod(pnev+100.,1.*(maxy-100)+1;
putpixel(xs,ys,color);
V1n<1+=xnev-x;
x=xnev; p=pnev;
h+=k/4./pi/pi*(1.-cos(2.*pi*x+(p-sig)*(p-sig)/2.;
nsum++;
266 E. Program Listings
{ sWitch(getch(
{
case 'e'
case n
case
II II
setviewport(10,maxy-20.maxx,maxy,l);
clearviewport();
outtextxy(l,l,str);
se V1ewpor , ,maxx,maxy,
case c setv1ewport, ,maxx,maxy-
clearviewport 0 ;
setviewport(l,l,maxx,maxy,l);break;
etch . break .
}/* while *1
}/* main *1
s1gma=.
nmax=1000
t[{x_,p_}] = {x + p + k/(2 pi) Sin[2 pi x],
p + k/(2 pi) Sin[2 pi x] }
plot3[xO_:.06,pO_:.34]:=
(xl=Map[First, NestList[t, {xO,pO}, 99]];
wind[xO_:.0838,pO_]:=(w1=xlist[xO,pO]j
(w1[[-1]]-w1[[1]])/nmax )
hpO:=Table[{pO,h[.0838,pO]},{pO, .2, .4, .01}]
p 0 is 0 p, rame-
rame a e - p , energy ,
PlotStyle -> PointSize[O.013]]
hxO:=Table[{x,h[x,.336]},{x,.15,.2,.001}]
a Ice: slerp.c
***** Fractal Lattice *****
#include <graphics.h>
#include <stdlib.h>
main 0
{
" .
getch()j setcolor(WHITE)j
while ( !kbhitO)
268 E. Program Listings
'\ . . VA 1 (nt:
' . Y.
.nt: .v. WH Tto: J
getch();getch();
closegraph();
}
.,
,\,.&...i> .. ~ ,y.&.u
..:J":2'\.
.,.
1
J
."1
,
~
list2=Map[mult,list];
list=Flatten[list2,1];
plotlist=Map[Polygon,list];
Show[Graphics[plotlist],
ASDectRatio -> Automatic]]
IFl.nC.LUQe ~Sl;Q.Ll.D.n,;>
JJl.nclu<1e <math.h>
'include <string.h>
#include <stdio.h>
~.
.... ..:1
N 10
~.
.... ..:1
2 20
float runs=O,correct=O;
p"
main \inl; argc, cnar argv LJ J
1..
int neuron[N2J,l.nput,i;
float weight[N2],h,wsum,kappa=1.;
char ch,str[100];
FILE * fn'
.
if (argc==1)
{
printf(" Input file name? II) ;
SCanJ: \ ""f:> , S...r J ,
.t
else strcpylstr,argvLIJJ;
if ( (fp=fopen (str, "r ll ==NULL)
E. Program Listings 269
r,
~
,
exit(1)j
~ III
...........
'1:'," OJ
0" ~..,
~
.....
"I
..,~"'.
II
........ , ..
.\
}
printf(1I File Yes is being processed lI. s tr)j
r.
case ' 1' : input=1j runs++jbreakj
case ' 0' : input=-1j runs++;breakj
default continuej .
.t
for(h=O . i=O ji<N ;i++) h+=veightlij*neuronlij;
for(vsum=O . i=Oj i<Nj i++) vsum+=veight[i]*veight[i]j
if(h*input>O.) correct++j
;~( l\*;nnnt: < *Cln.,.t: (IolClnm) )
-
.,: ......(;.. n.; LW . ; .&-~ , u':; ...,..},.+ r;,.&-= -
.- , - -
.
4' __ f..: _1>1'1_-4 ..: ..... n
- , -, ~
..: __ ,
1- ,
r;, /(41 ... ",-t:)W .
---_.- -..-..-- ---_.- ..- -...
r..:1_ r..: _-4 1
-~ .
neuron[O]=inputj
}
if(runs!=O)
prl.n'tIl"'\n 7.tl.VI Va~l.C1 l.npu'ts"'.runsJ;
prl.ntf(lI\n 7.6.2f 7.7. predl.cted correctlyll.correct/runs*lOO.);
fclose(fp)j
getchO j
}
Euler[f_.y_,yO_.{x_.dx_}]:=
"r --
.. _. -." -. ,,_r -. -- -"
NestList[EulerStep[f. y. #. N[dx]]&, N[yO] Round[N[x/dx]]
]
naml..1l;On = p ~/~ \;OS -
LqJ
tmax = :lUU
dt - 0.1
phiO = Pi/2
270 E. Program Listings
1'\ _ 1'\
I'v v
~ ~-
L' - v.vo
phase:=RungeK[{D[hamilton,p],-D[hamilton,q]},
{q, p}, {phiO,pO}, {10,dt}]
plot1:=ListPlot[phase,PlotJoined->True,Frame -> True,
AspectRatio->Automatic,
FrameLabel -> {"q","p"},
RotateLabel -> False,
PlotRange -> {{-2.3,2.3},{-1.85,1.85}}]
.. . r f. .~. r ..' .'\.
.....
.... _ft . YI
'include <graphics.h>
'include <stdlib.h>
'include <math.h>
*inc.Luue ....sl<uio.Jl....
JF1nCJ.uae \~C\reC1peS\nr.n'
'include "\tc\recipes\nrutil.h"
'include "\tc\recipes\nrutil.c"
'include "\tc\recioes\odeint.c"
:1:;" ... 1,,11... lI\tr-\
.. :\rlrae e"
*; ...... 1,,11 ... 11\+ ... \
.. ,\.. . 1r4 ..."
double dt=.1,r=.25,a=.5,pi,ysc=3.;
int poincare=O,done=O;
in~ maxx,maxy,ximage,yiWA~e;
vo1<1 pr1nt(.),<1er1vs(.<10uDJ.e,<10uDJ.e.,<10uDJ.e.),event(.<10uDJ.e.J;
main()
{
int adriver=DETECT,Q'Dlode'
;"1: i "nw "hAtt Ynlttvnltt Y"iRV V"AV'
" "
double y[3],f[3],t=O.,eps=1e-08;
E. Program Listings 271
..........0 .. -r
10. ..J
-o,;~
.
.. ..... , ...
. , " .... ,..,,'\
,,\ \
., "
.
WGAA-'!lO:; .\ / ,
maxy=getmaxy()j
ximage=maxx-20j
yimage=maxy-110j
pi=acos(-1.)j
y [1] =pi/2. j
y[2]=O. j
.. . f\
.
_. ... ,,,
\,",u.u.o:;--u/ ,,'
{
if (kbhit 0 ) event(y)j
if (poincare==1)
{
odeint(y,2,t,t+3.*pi,eps,dt,O.,inok,inbad,derivs,rkqc)j
xold=fmod(y[1]/2./pi +100.5,1.)*ximagej
yold=y[2]/ysc*yimage/2+yimage/2j
., . . (.. . ,,'~ , '.1 ,,'~ ....... ,~.&. .......
-g' " ".1 ._'
,~.&. . .,\.,
_ .L~ .....
.., .. .. ..... r" ,
J
else
{
xold=fmod(y[1]/2./pi +100.5,1.)*ximagej
yold=y[2]/ysc*yimage/2+yimage/2j
odeint(y,2,t,t+dt,eps,dt,O.,inok,inbad,derivs,rkqc)j
xnev=fmod(y[1]/2./pi +100.5,1.)*ximagej
ynev=y[2]/ysc*yimage/2+yimage/2j
;i'(anl:l(vn""u-vnlt1"
+=+.&.~+
.
. - I?) l;n",,(vnlt1 vnlt1 vn""u vn""u)'
'J ,
.
1..
}
closegraph()j
}
"
I I 1'\ . '
... _..... .... 1'''' ......... " , ,
default: getch()jbreakj
case I i I : a=a+.01jprint()jbreakj
case 'd ': a=a-.01jprint()jbreakj
case I + I : ysc=ysc/2. jprint() jbreakj
case '-' : ysc=ysc*2.jprint()jbreakj
case I s I : y[1]=pi/2.jy[2]=O.jprint()jbreakj
case 't ': poincare=!poincarejprint()jbreakj
'~~ 4? "#11='1")' . "(1~ 4 40 4)
.'..
c:asl'! I,.. I
.
~(lI'Ji~lI ''''.\ ........, ... +(\
~ .
.l.
}
272 E. Program Listings
".+,-.toggle,clear,arbitrary");
setcolor(LIGHTGREEN);
rectangle (9 9 ximage+11 vimage+11l'
.l~,.. - -
.. p<_,; ... +oF(
.r
IIIH I ....
...
...="'1 oF II ....
II .. ="'1 oF
.. ...
,.
if(poincare==l) sprintf(lstring[strlen(string)]," - Poincare");
outtextxy(320,yimage+40,string);
setviewport(10,10,ximage+l0,yimage+l0,1);
;
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
1t; 'nrlnrl... <m~1:h. h>
double e=.5,a=O.1;
maine)
1.
v01d 1mage(vo1d), pr1ntl double.double,double );
double k(double),step(double *x,double dx,double*y,double*yml);
int gdriver=DETECT,gmode;
int xs,ysnew,ysold;
rlnnhl ... rly=10 I~OO 0 . =10 I~oo v vm1 "vn1 -'
=.O~
..
.
~ ...= nE;: 'V' 'V'P<1 vm1
-r
" "
..
initgraph(lgdriver,lgmode,"\\tc");
image();
Wh1.1eU)
{
x=dx/2.;y=yml=1.;ysold=1;
E. Program Listings 273
default: getch();break;
case '+J : e=e+de;print(e,de,dx);break;
case J_ J . e=e-de;print(e,de,dx);break;
case 's J : de=destart;dx=dxstart;e=O.Ol*(int) (100*e);
print(e,de,dx);
break;
case J1 J : de=de/10.;print(e,de,dx);break;
1..1. _ ' ....l.. .. 1
,
'r . . . . .
............. J..:I J . . :1 ....=..:1.... /" ........; ... + ( ..... . :I.. . . :I....'.' ..
.
.J ,
," _'L ' , J
"
}/* main */
double step (double *xa, double dx. double *ya, double *ym1a)
i.
long i.n;
double k(double);
double yp1,x,y,ym1,xp1,xm1;
for(i=l;i<=n;i++)
{
xp1=x+dx;
xm1=x-dx;
yp1=(2.*(1.-6./12.*dx*dx*k(x*y
-(1.+dx*dx/12.*k(xm1*ym1)/
(1 .l'Iv*l'Iv/1? *1r(v....1".
__ '1-_. ____ '1. - ... .
_._- -,- r-
.-t_ _.-t
1.... -1' 1 -1t' .. ,
}
*xa=x;
*ya=y;
*ymla-yml;
return yp1;
}
void
.[
. (I'In"hl ... A I'In"hl ... dA I'In"hl ... dy)
- ,- .. - ... ,
_\,~ _ _ +_r'll\nl
clearviewport();
274 E. Program Listings
setcolor(WHITE);
sprintf(str," E= X12.8lf , de=X12.8lf , dx= X12.8lf ". e .de.dx);
outtextxy(10.290,str);
re urn;
void image()
double k(double x)
{j.max}];
ListPlot[xulist,PlotJoined->True,PlotRange->All,
Frame -> True, Axes -> {True,False},
E. Program Listings 275
.
... ...... : - :
, .... ~,.
~ ....t'~
.. :""~"
... , 1.:1.
......._"
\-1'- --1''' -~.. -':'JI\~U.A. ~JJ '- .-"" "J
step2[u_.v_]:= (upl=RotateLeft[u]; up2=RotateLeft[upl];
uml=RotateRight[u]; um2=RotateRight[uml];
v+dt(2(uml+u+upl)*(upl-uml)/dx -
(up2-2upl+2uml-um2)/dx3 ) )
init:=(dx = 0.18; dt = .002; upast=uPast=ustart; time = dt;
dt=dt/l0; upres = firststep[upast];
Do[ufut=step2[upres.upast];upast=upres;upres=ufut.{9}];
= ..... ...1+ = +-i ....... ,
_.._-...,. ,.
.. -... ,,-- .... -.. ... --
.r..:ll--... ......
'C
_, .... 02r.: .1n' ._/T~r ..' .... r ..' " I nnl\ .: ~
c "--' -r~ r. ' ,...,...,...
"'I
'
~.
1..:11...
~.
,_
----,
"
~ ... L"~W'C--, UUI. ...... .u-... ........... .u-~.J ,
Do[ ufut=step2[upres.upast];
upast=upres;upres=ufut;time=time+dt.{fin}];
Print [IITime ".time];
xulist = Table [{ (j-max/2) *dx, ufut [Lj+l]]}.
{j.O.max}];
ts = StringJoinP'u(x.". ToString[time] II) II] ;
UU = Interpolation[xulist];
- _-_. ._in . n . ... .
.
D1,...+r....' rvl rv 1 1. D1 .n _~A11
_- _-- .. _..-
-~ .~. ~ -
...
~ _,
. ...
... .............
..._. _ A ..... _ _ , .., ._
.,.,
... -
"'V"~"I"''G ,
r,... ,...,...".,
LV. VUI..1
u2[x_.t_]=-12(3+4Cosh[2x-8t]+Cosh[4x-64t])/
(3Coshlx-28tJ+Coshl3x-36tJ)-2
plot4:=Plot3D[u2[x.t].{t.-.2 . 2}.{x,-5.5}.PlotPoints->50.
PlotRange -> {-10.0}.
.. . -
Shading -> False.
A -'> Th; rol
- - "': _ 7'"'" " _~
.1\
r,- ',. - _. ',. r_1 .. .. . 11.1.
--.,
~ ~ ~
plot5:=ContourPlot[-u2[x.t].{t.-l.l}.{x.-10.10}.
PlotPoints->100.
ContourShading->False.
PlotRange -> All.
ContourSmoothing -> 4.
-
....
9 .. h ...l
........_,
_'> J'"+" " v ll'\.
_ ..... 1:".. ' - -
. .
... rn .. n n ~ LO"
1"1
...... ~, .... 1"
v.~~
.. ....
... .... n- ......A .......
I' I'
"'oJ ..
A ~ T.'I'YIlo_...l
&'
...l co ,'I_ --11-
-<;;>
~
. i
. 10
maine)
{
double r=O.;
.long l.;
printf("\n\n 1,000,000 random numbers are generated II ,
II and averaged.\n\n");
_. --
~ ., 'r.'. ..... 1 A
--00- '"' _.._--
. ,:11 ... '"
void main 0
{
void occupy(),jump(),aggregate(),circlejump();
,..h..... ."'- .. "\.
..... + ..:1_": - , _ .... ..:1 ......,
int i ,j;
maxy=getmaxy();
setcolor(LIGHTGREEN);
settextstyle(1,O,1);
outtextxy(5,maxy-40,1I Diffusion Limited Aggregation");
.1,.,.... tWHI -..:
,l.,.rn n 1\
-" ..
outtextxy(maxx/2+30,maxy-30,"Commands: exit, arbitrary");
randomize 0 ;
pi=acos (-1.) ;
J r " ,
.";~ "" .
while(1)
{
switch (checkO )
{
case 'k':occupy();jump();break;
case 'a':aggregate();occupy();jump()jbreak;
,. .. co ... ';'.;n_n(\.~........ 1r.
if (kbhitO)
switch(getchO)
{
case J e J : closegraph();exit(1);
default : getchO ; break;
}
}/* while */
~ .
~/. _ .. oi ... 1
....
yu ....... "
J ......l ' \ 1
{
switch(random(4
{
case 0: rx+=1;break;
case 1: rx+=-1jbreak;
case 2: ry+=1;breakj
case 3: ry+=-1jbreak;
~
~
'\.
J
void aggregate 0
{
double x,y;
xf lrx+lmax/2J lry+lmax/2J =1;
x=rx;y=ry;
rmax= max(rmax.sqrt(x*x+y*y;
if(rmax>lmax/2.-5.) {printf(I\7") ;getchO ;exit(1);}
oi.f:(
_..: .,
'/1nn==n,
fA
.1,..... (,.,..1,....... fl,
II') ..
,1,..... (, .1'\
.f_. __ _':11'\\ II') I')~'~
.
, , . _ - '---'" - _J '--J --" -,-"
J
void occupy()
{
double phij
phi=(double)rand()/RAND_MAI*2.*pij
rx=rs*sin(phi)j
ry=rs*cos(phi);
1
void circlejump()
E. Program Listings 279
r
~
char checkO
.f
rlnllhl ....... Y.V
... ,.......... ' .
y=ry;
r=sqrt(x.x+y.y);
if (r>rkill) return 'k' ;
1:r\.r.>:-ra) re'turn c' ;
if{xflrx+l+lmax/2JLry+lmax/2J
+xf[rx-1+lmax/2] [ry+lmax/2]
+xf[rx+lmax/2] [ry+l+lmax/2]
+yfrry+lm3y/?1 rrv1+1m3y/?1>O) , 3' .
... 1",... ,; , .
J '
"
.
l.
percgr . c is aVaiIaOle on
~
\jU- tU
~
J IVI amy.
.
I..... Percolation 1
'include <graphics.h>
'include <conio.h>
'include <stdlib.h>
'include <math.h>
..... ;ft(,
.
.r
int gdriver=DETECT,gmode;
double p=.59275;
int i,j,pr,L=700;
pr=p.RAND_MAX;
initgraph(&gdriver,&gmode,"\\tc");
for(i=O;i<L;i++)
for(j=O; j<L; j++)
;~( ...... ftrl{'<'n.... ' n"t-n;va1 (; ; WHIT":
.
&' &' &' 'J
g "," " J
closegraph 0 ;
}
.. T"lIo ..
tJ. ":I: C UJ.y J..I.J.CJ.
,... .. . J. &
. .\;
#include <dos.h>
#define L 20
#define VSEG Oxb800
main 0
.(
...n;.:1 C!A+T(.:Inn'hlA)
void event(void);
void frame(int , int);
char ch;
1nt mcs,x,y,e,v;
clock_t start,end;
clrscrO;
randomize 0 ;
mcs=O;
- .----- (1'0 1)
~~ ( l i T ....... ""
: ........
r ~
.f:.
~ "' .
gotoxy(50,2);
printf("Monte Carlo simulation");
gotoxy(50,3);
pr1ntI l '::system S1ze 7.d * 7.d' ,L,L);
gotoxy 0, 25) ;
printf(" Commands: l(over),h(igher),j(ump),e(xit),arbitrary");
frame(2*L+3,L+2);
for(x=l;x<L+l;x++) for(y=l;y<L+l;y++)
{
~ ~ p ~ p ,~p ~
Ly-.LJ
~
~5
p ~ p ,~
LXJ Ly . .LJ ) ,
.
1Il e<u II randlj<DILe/:lJ )
i.
s [x] [y] =-s [x] [y] ;
E. Program Listings 281
~nn n .~\-'-"'\.
.-- .. , "'";::';~,~
_", ... 1, I,
"~ ... : ""
'-U-,OLAJ L;YJT.LI '.LiJ,
poke{VSEG,v,OxfOOlch)j
/* gotoxy{2*{x-1)+3,y+1)j */
/* putch{ch)j */
} /* if */
} /* for */
for{x=ljx<L+1jx++)
{
a rn1
- - -r.".1'- =a rr
_. 1 r.".1
_._-
- ..- -.. ...... - .. -....-. ,
~-
~rT .~,r_,_~r~,r_,.
r."rn' r~_,r,.,
g LAJ LVJ -g LAJ L ...J ,
.. -, . ~ , ...
"" "
vu.a.u. ;:>.,. ... 4
{
temp=tj
bf[2]=RAND_MAX*exp(-8./temp)j
bf[1]=RAND_MAX*exp(-4./temp)j
bf[O]=RAND_MAX/2j
gotoxy(50,10)jprintf{" Temperature: Y..2f",temp)j
}
;.:!
u ....
r ""
" switch(getchO)
{
case 'h':setT(temp+=.05)jbreakj
case '1':setT(temp-=.05)jbreakj
case ' j , : setT (1. ) jbreakj
default :getchO jbreakj
case 'e':clrscr()jexit(l)j
1-
'\
~
gotoxy(1, 1) j
while (i++, i<xmax) putch(205);
for{i=lji<ymax-1ji++)
.(
'1 ; +1)
: ..... ~~(10~' ,.
,---,
.
gotoxy(xmax,i+1)j
282 E. Program Listings
, . ft""
. ~
, ., J
.T
i=O;
gotoxy(l,ymax);
while(i++,i<xmax) putch(205);
gotoxy(l,l);putch(201);
gotoxy(xmax,l);putch(187);
gotoxy(l,ymax);putch(200);
gotoxy(xmax,ymax);putch(188);
~
I
... .,
& ....
. n
OJ
T'" . LJ .' , ......,,,,,, ,.1 ... '~r!:
I I , .LV"", .L-S I , .LVU
A
A
" "
~~
Apply 4
-J ..1
char 5,225
o~,ou
.,
'11
r;:
~
" ... ~u
.1.
-~ u
...... -.-
LJ~~
, ,
--
UVU, - - ~~AV,J
,
~~
-u .....
oJ
- ...............
I, ~u, "'~~
'7C
~"A
'70 1<)1
v, .v, ....,... , .....,
~
1..11::
,-I, iJ.l,
...
U.l
~
Data - - generalized 60
- nOISY 22 - problem 66
- smoothed 21 Eigenvalues 49,62,76,221
default 112,229 Ei~envector 47,59,61,66,76
#define 5,125,227 Elliptic integral 7
Degeneracy 78 EllipticE 35
Derivative ,39,84 EllipticF 8
..
. .,. --...
lA'l 1:'"..:_... ..:_u o 1'1 'l~
...
...........
A' - - - . . ...." -_, ... ~
. .-
101"7 nno
...... '''- -. ,.
"1"7
.. ,.., ............. ,..
~OiJ,~~~,~~~
T'"'
.cJllU- lIV-t:llU
...u., """"u
..,..,.....................
~O"',~OoJ,~ou
~
An
~v~v~
... ,
~o
.......,
'lO
V" v
...... U
.""
- partial 136,144,148 Equations, system of 52,56
Diffusion 164,195,198 - linear 47,59
- equation 164 Equilibrium, thermal 190-192, 195,
- - radially symmetric 166 198,202,203
- limited aggregation 164 Error, local 118
Dimension Euler method 116, 119, 120
- embedding 102 Euler step 118,148
.. .1 1(\') 1')'1
, ---, l~A
--, 1'71 , 17A , 1'7~ 1:'..... 1 ..... + ... g
-
10'1
....... .Lv"',.Lv",
10n
-~
. .......
~,
-... orr
.,.., .. - rr - 1 ....
.L'2:U
.1..,
~
r-.
~
_1...1
~ '1'1l:::
v, __ '"
.. v
1"70
U
----
.. ---
"".
11 '1
11 n
.L.L""
Double-well potential 51,121,135 Fibonacci number 19
Index 285
- .
.... ;"'1~ ')0 ("1
. .". 1 nO 11 n
,. ...
- .., ,., _.-
.~.~ ~~
"
... ..,'"', ...... v
'In rt
vv VI
'[;I,'
~ ~J ~.~
.1 00 no')
~~,~-
.....
~_~
. .
u __
~
,
-
1 "70 1 Oil
...,,_~v
Flatten 62,74,105
float 5,225 Hamiltonian 48,51,71,73,75,119,
Flory, P.J. 182 149
fl'luctuatlOn 175,192,195,198,199 - normalized 145
Flux Harper equation 64,66,70
- area-preservmg 94 Hermite polynomial 48
- magnetic 64 Histogram 86
Ji'111'V J.Ti+ ..
~
'r--
.. 110')
-~-
RLl
IT" L.,.&
TT'-:'
;. , _.n 110 11'>
&:.').,
~~
~'l ,.,n
.........
... A
-.:,~
n1 n
... ., I 1 n
oJ
VV v
- 52,55,60,152,210
T.'I ~
, -v, _.. . _.. ,
"7 11l 1') 1')1 T ..
"-oJ
-_ .
11')..4
Function
u
I .... ,
nteractlOn
- Boolean 108 - attractive 183
- nonlinear 93 - magnetic 172
InteractIOn potential !J;j
Gam 42,44 Interference pattern 146,153
Game of chance 46 Interpolation 141
Game theory 42 Inverse 61,221
~ . 24 ~ ~
'lIer 15" 21
~~j;l ~Q 1?~
T 1
.1
n. .. .. ,
'>0 1~'l T
". u",l11 0 ~I:;.
gcc 6,240 Ising ferromagnet 192,197
286 Index
Isotropy 165
Iteration 84
- inverse 85,90,150
- rule 107
Leath, P.L. 177
Length 4,76,216
Line
Line integral 36
LinearProgramming 42,45 Network
Liouville's theorem 94 - electrical 52
Liquid 39 - linear 54
Nonlinearity 7
83,91 NonlinearRegress 25,217
Normal mode 60
,
132
185,191
Index 287
, ,
- superstable 84,85,90 Poincare section 82,94, 123, 126
Order Point 159
- magnetic 172 Pointer 5, 230, 233
r er parameter Polygon 10
Oscillation 138 Polymer configuration 183
- damped 126 Polymer dynamics 183
- longitudinal 59 Polymer molecule 102,182,186
Oscillatory circuit 52
54,58
27
23,28
37,214
, printf ,
9 Probability 43, 145
122 - density 164
172,175
74,216
49,83
y , ,
rand 5,103,158,168,177,206,230 - time-dependent 144
RAND~AX 5,168,170,230 Schroeder, M. 106
Random 4,158,159,214 Sech 138
random 96 Self-avoidin walk SAW 182
Random motion 164 Self-intersection 184
Random number 4,21,46,113,157, Self-similarity 104
205 Sequence, periodic 158
,
Richardson extrapolation 118 Spectrum 63
Rosenblatt, F. 109 Spin configuration 191
Rosenblatt rule 110 Spin correlation 80
RotateLeft 21,138,141 Spin lass 202
RotateRight 141 Sqrt 9,49,212
Round 119 Stability 143
Round trip 200 - condition 143
State 94
163 - commensurate 95,97
- incommensurate 98, 99
- initial 83, 150
- quasiperiodic 98
- stable 93
- stationary 47, 145, 191
Index 289
,
- stochastic 44 Two-cycle 83
Stroboscopic illumination 123 Two-person zero-sum game 43, 46
struct 103,178,186,205 Two-phase line 39,40
Sturm se uence 67 Two- hase mixture 40
Subharmonic 83 Two-soliton solution 142
Sum 32,75 Type declaration 5, 103, 225
Supercomputer 191 typedef 161,186,205
, , ,
switch 112,169,228 unsigned long int 161
Symmetry 66,68,69,74,78,131,133,
145,146,193 Vacuum 72
- reaking, spontaneous 19 van er s equatIon
Synapse 106 van der Waals gas 38
Synaptic plasticity 108 Variance 24,162,200
Synaptic strength 108 Vector 4,30,229
,
Transition probability 185, 191, 194, Winding number 95,97,99
196,202 - rational 97
Translation 60 Witten, T.A. 163
- opera or or 1ng reC1S10n
- t eorem
Traveling salesman 200 Zaman, A. 160
L
~'Gdby~
CN' ~
~
CP ;:,-
~
.)0~
L
~nrinn~r
-'" t"'. ~ ~
and the
environment
At ~pnnger we nrmly Delleve tnat an
international science publisher has a
special obligation to the environment,
and our cornorate nolicies consistently.
~ ~
permanency.
~
-~
~4~
~
Springer
w. Kinzel/G. Reents
Ph~sics
bq
C0m PUte r
Computational Physics has under-
gone rapid development in recent
years and is being integrated into
physics education as a standard part. This course,
intended for upper-division undergraduate or grad-
uate students, was designed by W. Kinzel and
G. Reents as a textbook in computational physics
but may also serve as a supplement to courses in
theoretical physics.
It is an introduction to the solution of physical models
by computer. The programs developed in this book
are based on the modern computer languages
Mathematica and C and are written for PCs as well
as for workstations. 28 examples from different fields
of physics are worked out, including chaos, fractals,
the Hofstadter butterfly, phase transitions, Monte-
Carlo simulations, percolation, polymers, combinato-
rial optimization, neural networks, and game theory.
Detailed explanation of the algorithms and computer
programs together with source files and graphics
routines help the student gain thorough experience
right from the start.
System requirements: Mathematica 2.2 or 3.0,
C compiler.
ISBN 3-540-62743-X
I I II
9 783540 627432
http://www.springer.de