Download Physics by computer programming physical problems using Mathematica and C.pdf...
w. Kinzel/G. Reents •
Ie
b~
ut
Programming Physical Problems Using Mathematica® and C
Springer
W ..
Using Mathematica® and C
Translated b Martin CIa·us and Bever! Freeland-Cla·us With 88 Figures) 33 Exercises and a CD-ROM Containing Programs and Graphics Routines for PCs
.
)
~
.
Prof. Dr. Wolfgang Kinzel .....
r-.
r-."
Dr. Martin Clajus r-.....
....
1
ve; ve;l£j'
~
.~..
1
-....,.vi.]US
~,
r l tV.-UU:.G. UI. Ut:UI ~ ...
Uf.
Institut fUr Theoretische physik UniversiUit Wiirzburg Am Hubland D-97074 Wiirzburg e-maIl:
[email protected] [email protected]
Deot. of Physics & Astronomv UCLA Box 951547
Los Angeles, CA 90095-1547, USA e-maIl: c1a}
[email protected]
The cover picture shows a space-time diagram of the probability of presence of a quantum particle in a square-well potential. This American edition has been revised bv the authors. The book was oriQ:inallv oublished in German: W. Kinzel, G. Reents: Physik per Computer, © Spektrum Akademischer Verlag, Heidelberg 1996
CIP data applied for Die Deutsche Bibliothek - CIP-Einheitsaufnahme Physics by computer: programming physical problems using Mathematica and C; with 33 exercises and a CD-ROM containing programs and graphics routines for PCs and workstations; Mathematica 3.0 compatible I Wolfgang Kinzel; Georg Reents. Trans\. by Martin Clajus and Beverly Freeland-Clajus. - Berlin; Heidelberg; New York; Barcelona; Budapest; Hong Kong; London; Milan; Paris; Santa Clara; Singapore; Tokyo: Springer. Einheitssacht.: Physik per Computer rCD'"
·v
This work is subject to copyright. All rights are reserved, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting. reuse of illustrations, recitation, broadcasting, reproduction on microfilm or in any other way, and storage in data banks. Duplication of this publication or parts thereof is permitted only under the provisions of the German Copyright Law of September 9, 1965, in its current version, and ••
(nr .. N' ...... d
;".,,,,,. ]"A
•
frnrn
•
. \7 ...1.
••.
•
"rA \;"],,!A fnr
•
..n,JAP .hA
© Springer-Verlag Berlin Heidelberg 1998
Printed in Germany Mathematica® is a rel!istered trademark bv Wolfram Research, Inc. ine .~se 01 ge~eral u ..,
v,
.,...,
1-'............
name~:.
,
,
•.
names. u
r
1-"
,en;. In mls.
HV'"
,....
•
.
. uoes nor implY' even . in .............
v
and therefore free for general use. Please note: Before using the programs in this book, please consult the technical manuals provided by the manufacturer of the computer, and of any plug-in boards, to be used.The authors and the publisher accept no legal . .. . .. .. :espUnSllJ~~lY lUI any ~aust:u lJy : • ust: UI lilt: .£1:. 'UI~ v llt:rt:I~:; '"
... ~ .. ~ .
. '"
•• ~,,~
v~~
..
,~~.~~
.....
~~.~.
.. v . . ~.
,~~~
"V
. v. . . . ~.
...~
•
. . . ~l
....
function correctly. The programs on the enclosed CD-ROM are under copyright protection and may not be reproduced without written permission by Springer-Verlag. One copy of the programs may be made as a back-up. but all further copies offend copyright law. ~Uver
uesigll: I\.UIll(r) = r
+ - r 3 + -rQr+O 2r 5
I
r(i) ~ 00,
(1.34)
1.6 Multipole Expansion
N
N
q
=
ei, i=l
where
ri
i
)
P=
31
ei r (i),
Q kl =
i=l
is the kth component of r( i) .
We want to investigate this expansion using an example of five positive and five negative unit charges that we place in the x-y plane, randomly dis-
rpoint:={2 Random[]-1, 2 Random[]-1, O} Do[r[i] = rpoint, {i,10}]
p1 = Graphics[Table[Line[{Drop[r[i],-1]-{O.08,O}, Drop[r[i].-1]+{O.08.0}}],{i.5}]] =
.
.
•
• •
Drop[r[i+5],-1]+{O.08,O}}].{i,5}]]
Next, we use Circle [ ] to draw a circle around each symbol,
o tions] to lot all four ra hies ob-
two vectors,
The dot between two arrays of numbers - Mathematica's extended notation for this is Dot [11,12] - effects a scalar product of the two vectors, i.e., the sum of the products of corresponding components of the vectors. Without the dot on the other hand the vectors would be multi lied element b element ei
= ±1 and:
32
1. Functions in Mathematica
...
..
1
c: ~
1
$
0.5
Ss
0
a:"'.....'J7
>.
""
S
EIb
'V'J
~
-0.5 $
-1 -1.5 ....
-...
,
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
Fig. 1.13. Positive and negative charges randomly distributed in the x-y plane
x
pot [rh_] := Sum[1/dist[rh.r[i]]-1/dist[rh.r[i+5]].{i.5}]
We present three ways to visualize this result: first we use Plot3D to plot the •
.1
r
•
,'I..
r.
,U.l
lJ.l.l{;;
.lV.l.l.l.l
r
.11
" ............ J'"
V.l
..
..1
~
(ld..lU
r VUlJ
V.l
.'1.. lJ.l.l{;;
"'"
-Y
,
1 A
next, we plot the contours 01 thiS mountaIn range lJy usmg (;ontourPlot; finally, we calculate the electric field and plot it via PlotVectorField, from the package Graphics" PlotField'. In order to see anything in the latter case, however, one has to normalize the field, i.e., display only its direction. The dinole and auadrunole moments can be formulated lust as easilv in Mathematica. According to (1.35), we have dipole = Sum[r[i] - r[i+5].{i.5}]
._ .. ......:.....,_r_, r~-- ..r r,~" _.. . 'L'"
... L L .... .J .J
q~wn
-~
T~
. r r .. "
.........
i LL·L~JJ
,..,
r" __"
...... L ....'
... L L ... .J .J ~
' ............ ~
-
~
-~
..
r,o
....
r ...... ,
........ .I.~ ........I.J _.... r. _ , ..
v.J.~
...
'LL'L~"OJJ ,"l~,OfJ
Here, the Kronecker symbol 8kl is represented by the following expression: .
~
.~
.LI LK==.L • .L • UJ
To calculate the magnitude of a vector r, which we could also express as dist [r ,0], we use the function ma~n[r
]=Sart[r.r]
With this, the expansion (1.34) of the potential 4>(r) can be defined immediately. In our example, there is no net charge (q = 0); therefore, the first term pot 1 is the dipole term, and pot2 contains the quadrupole term in addition: po'Cllr_J - Q1p0.1e.r I magnlrJ,j pot2[r_] = pot1[r]+1/2/magn[r]A5 r.qsum.r
Here, qsum is an array of arrays, in this case a 3 x 3 matrix; r is an array of
n11Tn
hPTQ 1 P
r.
,
.lV.l
l.J.l{;;V.llJ'y,
.1
:l. "
'T'hp
.
nof: r
r_ .r
V.l
1
..1"
,.
" .'1..
,0
vv .llJ.l~
a..l.l
a..l
...'I
hv
:l.
rlot (.,
oJ
'.1
•
, .~ V.l
indices (= nested arrays). Therefore, in this case the quadratic form "vector
1.6 Multipole Expansion
33
conventIOn programmmg nest two for loops:
for(j=O; j ----, v -> 3b}} ?7 h
Since the solution is not always unique, Solve yields a list of rules; hence the double curly braces. We obtain the critical pressure by applying the inner Dart of the rule to D, oc = oj .sol[[1]]
with the result a/ (27 b-2). Now we define the normalized function p(V) from (1.43): . ., 0'" ,,,,,v -"", v 10 }lLV_J ....
J , ....
..,
.... J
_ ....
-~I
For the two-phase line we need two equations in order to determine the two unknown volumes vi and v3 between which gas and liquid coexist. The first
..
""',," t'h",t -J
eq3=p[v1]==p[v3]
.
,~
"'1
..
an" '" H t" nf ~
r
1.8 Maxwell Construction
'1"'1-. ~
.J
.&. ........
~~~
""........
41
..
.. 1-.~ .. ~.~ ~_~~~ .. ~ {1 AA\ • v........ v ""................... ..............""............. 0 V"" \.L ..... J •
..
eq4=p[vl]*(v3-vl)==Integrate[p[v].{v,vl.v3}]
An attempt with Solve indicates that Mathematica does not find an analytic solutIOn. '1'heretore, we wil1 use FindRoot to obtam a numencal solutIOn. '1'0 find a reasonable result, however, the initial values of the (vi, v3) search have to be specified rather precisely. Therefore, for temperatures T < 1 the function plot [T _J first determines those values of v where p [v] attains its local min-
.
and
..
.
..
.. I. ~ l I r il. V"''''', V" ....... " • .L ............. v .........
...
'1"'1.
•
V~IV
and ~
•
1
thp.
.-t. •
.
•
of thp.
., .,
r .....
.J '" . , r. r ..' .... v~V .... L'p LV.I
i'
-.PLV" ....... ".I ,V.I .. ,,-
turns three solutions; the two outer ones are suitable initial values. The final Maxwell function then is "Dmax[v J:= If[v < vi II v > v3. "D[V]. "D[v1]J
Thus, if v is between the solutions vi and v3, the two-phase line is returned, otherwise it is p[v]. Fig~re 1.19 shows the result for various values of the normalized temperature T, together with the unphysical functions 'P [v]. As '. • 'IT _~ 1 /1. tho iho'l '1"1(17\ in tho CT~'l 'T'ho tnn ., ..... r, I .... ..... phase, and the next lower one represents the situation just at the critical temperature. The three lowest curves show the separation into a liquid (small O'
,
,
J.J.J.
.
.) ~mrl ~. .....
• ~"i'
... ,
.
.
A )onu t.hp .. ~.~
.1-
.....
.
linp
.1-
1"
..
'.J
.
~.nrl U~R
.....
2
--
1. IJ
\
1.5 1 ')l\
\
c..
~
\~-~ --
1
0.75
\/
f\,
~.~
~......-.-..
/
\/
0.25 0
1
4
j
1.
)
V "":...
·0·
..
_e
.. 0
,.
--
..
l\Jf
, -s.-
~~_ ..1-."
. .vtJ, .v, .. ~ ..
,;:,
~
oL
.L
~~
v .... ~
~
.L
u
....
~ ..:1,,_ "'X7........ 1...
~ ....
~ ~~
~~..
~~"
v.~tJ, v'~"',
-~
~
~~
,
~'1'
V.otJ \ "up loU
,
T... ~ ..·-
,
-
,
~~_
..1-."
.. ~ ..
v .... ~
42
1. Functions in M athematica
Consider a quantum particle of mass m in a one-dimensional potential well for - a 0 and 1 + 2 + 3 + 4 = 1 we have choice i,j
From this inequality, one can derive a system of four conditions, since with o
LP?Kij
> K o for all j
If we assume that l:X?Kij
~
> 0 then with
> 1 for all j
(1.51)
.
.
x·
. K 0 this becomes
(1.52)
i
Xi _ , e 1m = Koxo and the associated average gain K o are determined by a minimum of c . x with the added condition KT x > b, where the latter vector
Xl,X2,X3 strategy Po
WI
C, since with qo = Koyo one obtains
1.9 The Best Game Strategy
45
Then, analogously to (1.50) and (1.51), for any strategy P of R: o.
i,i
This means that in the worst case player C, using an optimal strategy, will
The minimum of a linear function c . x with the added conditions KT x > b and x > 0 can easily be determined using M athematica. For our example we
= {1,
1, 1} b = {1, 1, 1, 1} k = {{o, 1, 3, 1},{-1, 10, 4, 2},{7, -2, 3, 7}} c
and LinearProgramming[c,Transpose[k],b]
Instead of searching for the maximum of b . y we can search for the minimum of -b . y just as well. The inequality Ky < c is equivalent to
This yields the vector Yo and consequently K o = 1/(b· Yo) and qo = Koyo· For our exam Ie the calculation ives the results Po =
This means that R uses an optimal strategy if he chooses rows 2 and 3
46
1. Functions in M athematica
this matrix. For each move, the player chooses one of the four rows; at the same ti~e, the computer selects one of the columns with the ~robabilit.ies
qJ.
notice, however, that the computer wins in the long run, unless its opponent calculates the best strategy p~ and acts accordingly. At the end of the game
Exercise n extend the well-known arne of chance with the three s mbols rock, paper, scissors to the four symbols rock, paper, scissors, and well. In this version, two players each pick one of these four options and win or lose one oint accordin to the followin rules: • s iss rs. • Paper covers well, paper wraps rock. • Scissors cut paper. • Rock smashes scissors. Formulate a payout table for this game and use it to calculate the optimal strategy for both players.
von Neumann J. (1928) Zur Theorie der Gesellschaftsspiele. Ann. Math. 100:295 [English transl.: Bargmann S. (1959) On the Theory of Games of
2. Linear Equations
(with the exception of the Hofstadter butterfly) in such a way that they can be examined using predefined functions. When we deal with the electric cir-
2.1 The Quantum Oscillator The e uation of motion of uantum mechanics the Schrodin er e uation is linear: Every superposition of solutions is itself a solution. Therefore, the method of separating the equation into a space- and a time-dependent part b a roduct ansatz and later su er osin these roduct solutions is success-
, of a linear differential equation. The solutions of this equation are wave functions !P(r), which assign a complex number to every point r. More specifically,
48
2. Linear Equations
Physics
,
in the quadratic potential V(q) = mw 2q2/2. Here, q is the spatial coordinate of the particle. In dimensionless form, the Hamiltonian of the system is
Here, the energies are measured in units of liw, momenta in units of ../limw, and lengths in units of JIi/(mw). The eigenstates Ii) of Ho can be found in
.
. .
'Pj (q) = (2 j i!0f") -
e -q 21lj(q) ,
where 1lj(q) are the Hermite polynomials. We have 0_' J
The c~ are the energies of the eigenstates of H o, and the matrix (iIHolk) is diagonal because the eigenvalues are not degenerate.
.
H
= 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 =
=0
= VI Ii -
(2.5) 1) for i > 0 . Consequently, the matrix representation of q in the space of the unperturbed a 10)
=
and a Ii)
~ Vk + 15j ,k+l + ~ Vk5j ,k-1 = ~ J j + k + 15!k-jl,1 '
(2.6)
The a roximation that we will now use consists 0 de nin this in nitedimensional matrix for i, k = 0,1, ... , n - 1 only. The Hamiltonian H = Ho + Aq4, or more precisely its matrix representation, is to be approximated b an n x n matrix as well, where H o is re resented b the dia onal matrix eigenvalues of H for different values of n.
2.1 The Quantum Oscillator
49
The construct Ihs : = rhs /; test means that the definition is to be used
q[n_]:= Table[q[j,k], {j,O,n-l}, {k,O,n-l}]
and according to (2.2) Ho is calculated as
With this, H can be written as
Results
The call
ields the Hamiltonian matrix
/ MatrixForm
o
(2.7)
3
o
1. 2
+ 154 ).
Its eigenvalues are
discrepancies from the exact result.
2. Linear Equations
50
~
~
Q
~
8 7 >.6 ~5
~ 4 3 2 1
~~
~
---
. ,..
Fig. 2.1. Approximate valut:::i lUl'
0
0.2
0.4
0.6
0.8
Lllt:
'"
luur t:ll-
ergy eigenvalues 01 tne quantum osCillator with the anharmonicity Aq4, as a function of A
1
lambda
How accurate is the approximation? This can be seen in Fig. 2.2 for the example of the ground state energy co. For an anharmonicity parameter A = 0.1, co is plotted as a function of lIn, for n = 7, ... ,20. Obviously this function is not monotonic. Althoue:h we do not know its asvmntotic behavior 4o'h .... WAA~
. 1. ~A~~
mat Ii ~
&~A
~ "" non h .... ~-
~~A
~~
'r>
.1
'S:
.
U ...."'U ~AJ
A
1
llu ".
-
J
.
~~AAAO
4o'h ....
.1 .
~AA~
= N[h[n] I. lambda -) 1/10, 20]; = Sort[Eigenvalues[mat]]; Ii [[1]]
",h4o o'n
f t .....
~"''''.... 'v
+'h ....
WAA~
~"'p
&~AA~
. AAAO
uo:>l ......'" ~"'''' .... &~A
')f\ o:>nrl .... 'v
•
_~
Af\.
~AA~
&~.
(20) = 0.559146327396 ... , co (40) = 0.559146327183 .... co
Tneretore, tor n - ~u we nave an accuracy 01 aoout mne slgmncant ngures. Higher energies can only be determined with less accuracy. We obtain clO
(20) = 17.333 ... , ~'I'o\
ClO \
f = 1 and R = 2700 n (right)
0.3
0.8·
0.2 0.1
0.6 • 0.4 :
. :
OJ-L.~:~·+4-+-.............-+-:;...++-0---+---;--1-1--1
-0.1 :
i
o
0.5
1.5
2
2.5
3
% 0.2 >
. :
0~·:------1'--~--+----:----t----1
1.5
0.5
2
2.5
3
tIT
tIT
,
copy of the input signal that results for
f = 3 and R = 5 n (right)
For R = 0, i.e., if the ohmic resistance is equal to zero and the circuit is therefore loss-free, the denominator vanishes at
w=
first for a general element with a complex impedance Z, through which a
58
2. Linear Equations
Fig. 2.9. Magnitude of the output voltage for the network of series and parallel cir-
lon, 30n, and 90n
P
= ~ (Re I (t) Re V (t) + Iml I (t) 1m V (t) ) 1
=
~ (Iz Vi + IzVz) 1
=-
z
where we have set Vz = ZIz at the end. For the ohmic resistance R, t e power is accordingly ~(w) = IIR(w)1 2 R12. We compare this to the power Po, which results if all coils and capacitors in our network are short-circuited, i.e. i t e in ut vo ta e i is connecte nect to t e resIstor ,so t at one gets IR = Vii R, and therefore Po = IViI 2 /(2R). The power ratio P(w)1Po is shown in Fig. 2.10 for R = 10 f!. At both resonance frequencies the coils and capacitors appear to be completely conductive, while at w = 1 ..jLC the
Exercises
1. Calculate and draw Vo (w).
.
.
issipation in t e two resistances as a unction
0
w.
2.3 Chain Vibrations
0.2
59
Fig. 2.10. The power P(w) dissipated in the ohmic resis-
connected directly to R
Iterature Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Redwood City, CA
2.3 Chain Vibrations
the model solid can be represented by superposition of such eigenmodes. SICS
We consider a chain consisting of pointlike masses ml and m2, which we designate as light and heavy atoms respectively, for sake of simplicity. The particles are to be arranged in such a way that one heavy atom follows three i t ones. The unit cell of len th a thus contains four atoms. Onl nearest neighbors shall interact with one another. We limit our considerations to small displacements, Le., the forces are to be linear functions of the shifts of the masses, as indicated in the s rin model shown in Fi 2.11. n,
and t n be the displacements of the light atoms from their rest positions, and
60
2. Linear Equations
Fig. 2.11. Linear chain consisting of two types of atoms which are connected to each other by elastic forces
mtSn mt in
= 1 (t n + Tn - 2s n ) , = 1 (Un + Sn - 2tn ) ,
(2.17)
,
,
hold for every unit cell n E Z. For a finite chain consisting of N unit cells we assume periodic boundary conditions, that is, we think of it as a ringlike
.
.
, invariant under the translations {Tn, Sn, tn, Un} --+ {Tn+k' Sn+k, tn+k, Un+k}, k = 1,2, ... , N, (2.17) can be solved by applying a Fourier transformation.
Xn
(t)
=
= S (q) exp (iqan ± iwt) ,
(2.18)
where, owing to the periodic boundary conditions, q can only take the values qv = 21rv/(Na) , v= -N/2+1, ... ,N/2. Then ields
- 1 0 - le- iqa 21 -I 0 which is a generalized eigenvalue equation of the type
, 2
,
w (q) and the corresponding normal modes S(q) for a given value of q. In our
2.3 Chain Vibrations
M- 1 F8 = >'8 .
61
(2.22)
This is an ordinary eigenvalue equation for the positive semidefinite Hermitian matrix M- 1 / 2 FM- 1 / 2 with the eigenvector M1 / 2 8. The ei enmodes X n t = 8 l qll exp iqllan ± iWlIlt thus obtained are pargously to the electrical filters (Sect. 2.2), the general solution can be obtained by a superposition of the eigenmodes. From the complex conjugate of
The coefficients elll, which are not yet determined, are fixed by the initial
Algorithm and Results
The 4 x 4 matrix (2.22) does not represent any particular challenge to an anal tical solution of the ei envalue e uation. If we consider several different types of atoms, or the corresponding two-dimensional problem, however, the matrices become so large that only a numerical determination of the vibration modes is ossible. We want to demonstrate the latter usin our sim Ie
choosing a = 1: matt
={ {
2f t -ft
Ot -f*Exp[-I q]}t
{ Ot -ft 2f t {-f*Exp[I q]t Ot -ft
-f}t 2f} }
case, Mathematica is still capable of specifying the eigenvalues in a general
62
2. Linear Equations
nested square and cube roots;
{x.-Pi,Pi.Pi/50}]
Flatten [ Table [ Map[{#[[1]].Sqrt[#[[2,k]]]}l. eigenlist], {k,4}], 1]
in Fig. 2.12. As we can see, the allowed frequencies of the lattice vibrations form four bands. The lowest branch represents the so-called acoustic phonons,
3r.::::=============1 2.5 ~
bO
e o
Fig. 2.12. The frequencies of
..
.. .. e----
•
• • •
• •
.. ;0
• • e----
..
..•
54(0)
•
52 (0)
53 (0)
1
Fig. 2.13. Eigenmodes of the chain for q = 0
2.4 The Hofstadter Butterfly
63
Exercise
Investigate the two-dimensional vibrations of your single-family home. Five equal masses m are coupled by springs, and the potential between neighboring masses is
D (Ir· - r ·1 - a· .) 2 J
V (r· r·) J -- -2 ~,
~
~J
,
the sides and the roof, and aij = V2l for the two diagonals. Calculate the frequencies of the vibrations for small displacements and
Literature
Goldstein H. 1980 Classical Mechanics. Addison-Wesle Readin MA Kittel C. (1996) Introduction to Solid State Physics. Wiley, New York
Linear equations can have intriguing solutions. This becomes especially apparent in the case of a crystal electron in a homogeneous magnetic field. The electron's ener s ectrum as a function of the stren th of the rna netic eld has a complicated structure reminiscent of a butterfly. This problem was investigated in 1976 by Douglas Hofstadter. Amazingly, the differences between rational and irrational numbers become evident in this s ectrum. We want
butterfly.
64
2. Linear Equations
We model an electron on a square lattice by localized wave functions and matrix elements for jumps between nearest neighbors. In such a tight-binding
..
£
(k) =
£0
.
.
.
(cos kxa + cos kya) ,
where a is the lattice constant,
4£0
(2.25) is the width of the energy band, and
t e vector potenti an p is t e momentum operator. For a magnetic field of magnitude B perpendicular to the x-y plane one can choose A = (0, Bx, 0). Thus one obtains the Schrodinger equation
E cp (x, y) =
£0
cos
Ii: + £0 cos Ii: +
cp (x, y) .
(2.26)
Owing to the identity cos a = [exp(ia) + exp( -ia)] /2, and because the term ex ia is the translation 0 erator that effects a shift b one lattice
Ecp(x,y) =
~€O [cp(x+a,y)+cp(x-a,y)
+ ex pIes cp(x, y) with the amplitudes at the four neighboring sites. For the ydependence of the wave function we assume a plane wave,
and with the dimensionless variables m
= x/a and u = a2 eB/ he we finally m·
Here, the energy E is measured in units of £0/2. This discrete Schrodinger equation contains only the parameters v and u. The parameter v determines t e -com onent 0 t e momentum w i e u is t e ratio 0 t e rna netic ux a2 B through the unit cell to a flux quantum he/e. With this equation we have mapped a two-dimensional lattice electron onto a particle that jumps alon a chain in a periodic cosine potential. The
, (= 1 in units of m). Here one can already see the difference between rational
2.4 The Hofstadter Butterfly
65
The eigenstates and the corresponding energies are classified by k and v. If one writes (2.29) in matrix form in the following manner,
with
then the q-fold iterated equation combined with (2.30), namely
Trace Mq (E)
= 2coskq.
(2.34)
or rational num ers u = p q t ere are at most q energy an s w IC one can calculate, in principle, from (2.34). In the vicinity of any rational number there are numbers with arbitrarily large q as well as irrational numbers q ~ 00, owever. onsequent y, as a unctIOn 0 u, t ere are spectra WIt large numbers of energy bands next to each spectrum with few bands. Here, the difference between rational and irrational numbers becomes evident in physics.
Algorithm
1 and q - 1, but select only those p for which p and q are relatively prime.
66
2. Linear Equations
The assumption that {'l/Jm} is, for example, an odd function of m, that is 'l/J-m = -'l/Jm, first leads us to 'l/Jo = 0 and then, taken together with the (2.35)
'l/Jq/2 +r = -'l/J-q/2 - r = -'l/Jq/2-r
en-
o Ao'l/Jo
= E'l/Jo , where
Ao =
o
o
o
1
.(2.36)
1
0
appropriate here, we want to demonstrate briefly that the treatment of those wave functions that are even in m leads to a very similar problem.
q
'l/Jq/2 +r = 'l/J-q/2 - r = 'l/Jq/2 - r for r = 1,2, ... , 2 - 1 .
('l/Jo, 'l/Jl, ... , 'l/Jq/2) T = 'l/Je of the wave function has the form
(2.37)
2.4 The Hofstadter Butterfly
67
o Ae 1jJe
= E1jJe,
where Ae
o
=
1
This two-part recursion formula is completed by the initial values PI (E)
= Vi -
E
and Po (E)
=1 .
(2.40)
,
0
q
-
The special importance of the polynomials Pn(E), however, comes from the fact that they form a so-called Sturm sequence: Sturm sequences contain
Po (E), PI (E), P2 (E), ... , Pq/2-1 (E) ,
then one obtains the result: is equal to
q c(E2 ) - c(E1 ).
-
C(Ei) and C(Ei+d then tell us whether there are any eigenvalues between Ei and Ei+l. The region in which any energy eigenvalues can be found at all
.
.
n
IE - aiil < ~ laijl·
(2.41)
j=l,j:# j=l,j#i
ij
conclude that the eigenvalues fall between -4 and 4.
68
2. Linear Equations
P2 Pn
-
(E)
= (Vn - 1 -
Po
E) Pn-l (E) -
Pn-2
(E) for n
= 3,4, ... , ~ ,
urm sequ nces, and (2.42), are almost identical to the Harper equation itself, for (2.29) leads to the following relations for the odd wave functions "p-m = -"pm with the
the P loop, where a(p, q) is varied, the ie loop, in which the energy changes between -4 and 4, and the inner loop over m, which is used to determine
for(q = 4; q < qmax; q+=2) {
2.4 The Hofstadter Butterfly
69
{
e = 8.0*ie/MAXY - 4.0 - 4.0/MAXY n = 0;
polyold = 1.0; poly = 2.0*cos(si if( polyold*poly < 0.0 ) n++ fore m
= 2;
a) - e;
m < q/2; m++ )
polyold
= poly;
poly
= polynev;
}
eigenfunctions has been left out here. if(n > nold) action;
}
, ((1- E) values to a data file. The function gcd (p q) used in the third line of J
the program calculates the greatest common divisor of p and q.
The result of this program can be seen in Fig. 2.14. The energy is plotted on the vertical axis, the parameter a on the horizontal one. The ener y is small interval, a point is plotted at the corresponding position. It is surprising and fascinating what a complex, delicate, and appealing
.
.
,
to any rational number a
= min
, (m and n relatively prime) with a small
70
2. Linear Equations
flux per unit cell Fi . 2.14. Ei envalues of the Har er e uation as a function of q = Ba 2 i.e. of the ma netic flux throu h the unit cell in units of the flux uantum
denominator n there ¥e also others with a large denominator, there will always be a large number of bands next to those values of (J that correspond o a sm enomma or. ny lrra lon num er can e apprOXlma e y a sequence of rational numbers with increasing denominators. Consequently, there will always be an infinite number of energy bands next to an irrational number. This results in the artistic drawing which, given infinite resolution, resists our ima ination. Exercise
butterfly and conceive an algorithm which bridges the many large holes.
trons in Rational and Irrational Magnetic Fields. Phys. Rev. B 14:2239
2.5 The Hubbard Model
71
, statements. Add to this a considerable mathematical apparatus in which the concept of states has to be introduced and operators have to be explained.
only be occupied once. In this space of the multiparticle wave functions, the Hamiltonian can be represented as a matrix whose eigenvalues specify the ener ies of the stationar states. analytic methods. But even a numerical solution is not easy to obtain. The size of the system and the increase in the number of degrees of freedom turn x q m-m mu p y m, w sider an electron gas in a crystal lattice. In dealing with this problem, we have to take into acc«?unt both the repulsive Coulomb interaction between the electrons and their interaction with the ion cores. A simplified description otIS SItuatIOn, w IC stl contams a t e essentla e ements, was su este in 1963 by J. Hubbard. Presently this model is being discussed in connection with high-temperature superconductivity. It is, however, still uncertain whether this model exhibits superconductivity at all.
In doing this, however, we have to limit ourselves to a few particles. Ph sics
annihilation operators, and the states can be generated by applying operators
72
2. Linear Equations
annihilation operators as well, so that the Hamiltonian matrix can eventually be constructed algebraically. e vacuum.
ctct ... ct
N
(2.43)
10) ,
(2.44)
(2.45)
result is O. The adjoint operator Ck annihilates cpk(r) if present; otherwise, the result is 0 again. The Pauli exclusion principle follows from = 0,
ctct
,
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) osed to feel the
If two electrons occu Coulomb repulsion
(2.47)
Unktnk.J,. . ,
,q
the magnitudes of the kinetic and potential energy respectively.
2.5 The Hubbard Model
73
M
H
= -t
(2.48) k=l
u
with Ck+l,u = cl,u and CM+I,u states, we choose
= Cl u '
For the order of the single-particle
Thus every multiparticle state can be described by the occupancy numbers of the single-particle states. Then we get, for example:
ct+ 1{1,0, ... ,O}, {O, ... ,0, I}) = ct+cttCk+ 10)
= -ct
t
c c
t
°
and
It
M+
= -ctt 10) + cl t ck+ cM+ 10) t
It = -1{1,0, ... ,O}, {O, ... ,O})
Generally, when applying
clu
or
Cku
to a state
the number of particles to the left of ku determines the sign. Therefore we define the sign function:
The function produces as many factors -1 as there are non-zero entries in n in front of the position ku. This fact allows us to write the effect of the
74
2. Linear Equations
Cku
In}
= nkusign (kG", n) I{ nIt,···, 0, ... , nM.tJ}
(2.52)
,
The following quantities are conserved in the Hubbard model: the number of particles with positive (Nt) and negative (N.J..) spins, the quantum number
.
.
..
.
be reduced to submatrices with a maximum size of 3 x 3. Here, we only want to consider Nt and N.J.. as conserved quantities. Also,
Once again, we want to use Mathematica to concisely formulate the repre-
s[arg] , where arg
= {{nIt,···, nMt} , {nI.J..,""
nM.J..}}
(2.53)
an nku E e nee t e ea er s ecause we ave to states and multiply them by scalars. If we were to perform these operations on the list arg itself, we would get incorrect results. The main manipulations, however, concern the argument of s. For example, one obtains nku from
After specifying the numbers M, Nt, and N.J.. we use the functions Permutations [. .. ] and Table [. .. ] to generate the list index, which con-
index = {{{1,1,O}, {1,O,O}}, {{1,1,O}, {O,1,O}}, {{1,1,O}, {O,O,1}}, {{1,O,1}, {1,O,O}}, {{1,O,1}, {O,1,O}}, {{1,O,1}, {O,O,1}},
2.5 The Hubbard Model
75
{{O,l,l}, {O,O,l}}}
The operator ct
has to generate a 1 in the right spot in the argument of s.
* s [plus [k, sigma] [arg]]
number 0 as well: cdagger[k_,sigma_] [0]:= 0
we still need the operators nklT: n[k_,si
a_] [0]:=
Then the Hamiltonian (2.48) of the Hubbard chain can simply be written as
,
,
cdagger [k+l, sigma] [c [k, sigma] [vector]] , {k,sites},{sigma,2} ]+ u*Sum[n[k,l] [n[k,2] [vector]] ,{k,sites}]
Here, the length M of the chain is designated by sites. In order to 0 tain the Hamiltonian matrix, we need the scalar products (niIHlnj) of Ini) with Hlnj). Since our multiparticle states In) are orthonormal, we only have to e ne t e inearit 0 t e sca ar ro uct: scalarproduct[a_,O]:= 0 scalarproduct[a_,b_ + c_]:=
76
2. Linear Equations
h = (hlist = Table[H[s[index[[j]]]]. {j. end}]; Table[ scalarproduct[ s[index[[i]]]. hlist[[j]]]. {i.end}. {·.end}])
g[uu_]:= Sort[Thread[ Eigensystem[ N[ h /. {t -> 1.0. u -> uu} ]]]][[1.2]]
k=l {n}
Mathematica's version of the right-hand side of (2.54) is
Since the sums are interchangeable and can be regarded as scalar products,
Results
2.5 The Hubbard Model
,
,
77
2u
, 3
Coulomb energy and kinetic energy. For U = 0, there is no interaction between the electrons, so we can calculate the energy levels simply by filling
-2
U/t
for M = 3, Nt = 2, and
N~
= 1
78
2. Linear Equations
fivefold degenerate: twofold degenerate:
£2
£3
= 0,
= 3t.
model. The average double occupancy rate in the ground state for M = 4 sites and the so-called half-filled case, i.e., Nt + N~ = M (in this specific
.
..
Hubbard ring with M = 6 sites, Nt = 3, and N~ 3. As moderate as these numbers may seem, the number of states strongly increases with M, .
6
6_
asM~oo
and compare the result to the corresponding values for M = 6. Surprisingly, the two curves are not very far apart at all, as can be seen in Fig. 2.18.
2.5 The Hubbard Model
o
2
3
4
5
6
79
Fig. 2.16. Average double occupancy in the ground state as a func-
U/t
-0.4,..-------........--..--------......
.... 8. -0.8 (/)
»
e.o
II)
-1
o
2
3
4
5
6
Fi . 2.18. Ground state ener er site for the half-filled band. The dashed curve is the exact result for M ~ 00, the solid curve gives the
80
2. Linear Equations
...,.
°
' - & 0 ....
The z-component of the spin operator at the site i can be expressed by the particle number operators nit and nq: Sf = (nit - ni.JJ/2. For the ground I _\
i:)IJaIJ'lJ
IY I
1". L VI.
TT."
,
.J.1· ,L
.u
IJU'lJ
.,
1I..r
VVI.IJ.U .U'.J.
A·
.J
1\ T
"% i:)J.IJ'lJi:) a u u J.
Yi
1\ T n ' J.
YJ. .',
•
.&I,
the spin correlations (11M) ~~:1 (glSf Sf+llg) and (11M) E~:l (glSf Sf+2Ig) as a function of U It. TO ,~uu..L'lJ
Hirsch J.E. (1985) Two-dimensional Hubbard Model: Numerical Simulation Study. Phys. Rev. B 31:4403 . 11 nn J:f,I H H f-oft. The inverse iteration is most easily performed in a coordinate system whose origin is at (x, y) = (1/2,1/2) and whose two axes are scaled by a . . . . . . :mcn tnat tne peaK or tne paraOOla in tne new system is at (0,1). In this coordinate system, the original parabola f(x) = 4rx(I - x) takes the form .1,
.
p
n
J
ft\ -
1
JL
r -"
l:lnrl ... l:l ....O
II
r
•
"t 2
1
,-,,/
A
= r (4r -
.... "ll:ltorl
,,; l:l
= ~ (1 + viI + 4JL) .
2) or r
We designate the left branch of the narabola bv or.(E) and the rie:ht one bv 9R(e). Then the superstable orbit for l = 2 obeys the equation 9R (9L (9R (1)))
=0
""yo
1 = 9ii (91:"1 1
(9ii 1 (0)))
with .1
9R
,
~'fJ)
/1- 11
V JL
.
ana 9L
/1- 11
.1
~'fJ)
V JL
.
This finally leads to the following equation for JL: I
a
= 1/V a + ..v/ a -
(3.9)
"fa
which can be solved by iteration or by using FindRoot. The sequence CRLR determines the signs of the nested roots in (3.9). After the initial CR, which does not enter the eauation above L vields a nositive and R a negative sign. This holds for all superstable periodic orbits. Thus, the orbit of period 5, with the sequence CRLRR, which is located between chaotic bands, is found at a a value that obevs the followine: eauation:
I f JL=yJL+VJL-VJL-YP;· We have programmed the generation of the sequence in Mathematica in the foP
~
w~.v· ., For p~("h
.,
.1.
.1
R (T,)
, "
WI"
.
t.hp mnnhpr~ 1 (I)). , , t.hp ~p_
quence of length 2n is stored as a list period [n] . Initially we define the list period[1] = {c, 1} for n = 1, and the doubling of the sequence is done by per1odln_J:= per1odlnJJoin [period [n-l], correct[period[n-l]]]
86
3. Iterations
sum is even. correct[list_]:=Block[{sum=O,li=list,I=Length[list]}, Do[sum+=li[[i]],{i,2,1}]; If [OddQ [sum] , Ii [[1]] =0, Ii [[1]] =1] ; Ii]
prec=30 maxit=30
In order to generate and display the orbits XO, Xl , X2 , X3, ••• for all parameters r (or J.t), one should use a fast programming language, if possible, since each value of r requires about 1000 iterations. In principle, however, this is very
until the X n have come very close to the attractor. Then, one calculates 1000 additional values of X n , transforms them into the y-coordinate of the
Xn ,
xit = 4.*r*xit*(l.-xit); putpixel( r*MAII, (l.-xit)*MAIY,WHITE);
following function:
3.1 Population Dynamics
87
}
getch();getch();clearviewport();return; }
Results
fixed points of the fourfold iterated function f(x). These can be seen in Fig. 3.2. The function f(4)(x) intersects the straight line y = x eight times, but onl four of those are stable fixed oints. As T is increased attractors ith
, ... Too Xn
= 0.89 .... This is clearly visible in Figs. 3.3 and 3.4, in which 1000
values are plotted for each value of
T,
after an initial transition period
0.8
,....,
0.7
c:
~ 0.6
Fig. 3.1. Iteration starting from Xo 0.65 using the parameter r = 0.87. The X n values move towards an attractor of period 4
=
n
3. Iterations
88
I...•
I
I
~ ••L-----------:t:----~ .:
~~m;
.. .;0; ••_-....
•
N
•••
;;..,;;.~.
~~_:o-.. . . . . . . ~-.• •~'~ ~_
....
below a five-cycle; though there is just one band there, one still sees the five peaks of the adjacent cycle. It can be shown that only one band with density
exists for r
= 1. In Fig. 3.4, in the chaotic region, one sees many windows with
baum constant 8. To this end, we calculate the parameters Rl, at which there
3.1 Population Dynamics
89
0. .
Fi . 3.4. A close-u
for
T
between 0.88 and 1
a parameter value T ~ 0.934, just below the window with period 5
90
3. Iterations
1
/ 0.6
f\A ~.
0.2
V
/
/\
/ // I
/
...........
./
0.8
/
/
I
/
/ \
/
\
\
/
1/
\
\
oV
0.2
0.4
0.6
0.8
Fig. 3.6. Superstable four-cycle with r = 0.874640
1
1
/
/' 0.8
/
"
/
/
V /
\
0.6 "
"
I I
0.4
0.2
/~
/
/
\
\
\ '(
1/
0V
0.2
0.4
..
,
Fi~.
\
..
0.6
-
0.8
3.7. Three chaotic bands for r = 0.9642, just above the large window with the three-cycle
1
.
. .
. .
.
VI. LJUlt:) or .?~I II II ,(.'. I lSI 19 tne TTlPT 'lnrl~ or symoollc aynamlcs are and inverse iteration we find the R, with a precision of 30 digits, of which only 12 are printed here: -0;-
11 "'...,,,....
fl. ~
•
'.LV
,
Ru R12
= 0.892486401027 , = 0.892486414339 ,
R.o
o on.n A 0'"'1.1 71 QO
li14 -
U.XU·IAW";A
'~u
R15
1'(~Ul
,
= 0.892486417932 .
•
.1
~ ••
3.1 Population Dynamics
we find the following approximate values for ~
= 4.669201134601
~12
= 4.669201587522 ,
~13
= 4.669201604512 ,
~15
= 4.669201608892 .
91
~:
From this we estimate that we have calculated ~ to 9 digits. The extrapolation m y, we want to mvestIgate a seemmg y SImp e questlOn: gIven Xo = 1/3 and r = 97/100, what is the value of XlOO? This seems to be easy to answer; with
the command Nest[h, N[1/3],100]
n y m ,prec , can specify the precision via prec. Now Mathematica reduces the calculated precision after each step until, finally, the variable X n is set to the value 0
92
3. Iterations
. . . ..
An
.. • . ....
. . ..
. ....
. . . .•
..".
.
(\
III
o
. ....
111111111111
40
20
60
n...
.: &5. u.o.
80
100
precision of the calculation
rn1~
~
,. ~"
oUt::
VJ.
XIOO for r = 97/100 as a function of the precision with which the calculation is performed. The vertical axis e:ives the number of digits to which Mathematica calculates the result of the iteration
Exercises 1. Calculate the Lvapunov exponent for the loe:istic map (3.1) as a function nf tho n. ~.
T
'I"
r , .
~11
~dt;11
1
,.
J11L~J
,1
VdJ 11J
, .
roo
Jom fi.-J., .l\.orSCn fi.J. \1~~LJ:) .n;.UlS: i\. rrogram \..Jouecuon IOr "(;ne C"\..J. Springer, Berlin, Heidelberg, New York Ott E. (1993) Chaos in Dynamical Systems. Cambridge University Press, ~
•• •
\ .:.:ITrJ.U5t::,
_y
_r.
l''1ew lurK
Peite:en H.O.. Saune D. (1988) The Science of Fractal Imae:es. Snrinlrer. Berlin, Heidelberg, New York Schroeder M. (1991) Fractals, Chaos, Power Laws: Minutes from an Infinite Paradise. W.H. Freeman. New York n H r.! (1 . . . t:lHllnQ· AnT , oo~,., n ., heim, New York ~,
1
3.2 The Frenkel-Kontorova Model
93
•
potential. We investigate only the rest positions of the chain elements. Both the spring forces and the external forces want to impose a distance of their
can take a large variety of forms. Ph sics
between neighboring particles, on the other. Then the energy of a long segment of the chain containing the sites XM+l, XM+2,' .. ' XN is given by
n=M+l
All lengths x are measured in units of the period of the external potential,
.,
v (x + 1) = V (x)
.
(3.11)
In the rest position, all forces on any given particle cancel each other. There-
---=V 8x n
With the definition
this leads to
or, transformed to the inverse recursion,
(3.12
94
3. Iterations
Pn-l = Pn - V' (xn-d .
(3.15)
From (xo,Po) - equivalent to this is the specification of (x_I, xo) - one ob-
.
.
,
of a continuous dynamic in three-dimensional phase space. So far, the potentials V and W have not been specified, but now they
..
.
(3.16) K determines the strength of the external potential, and u is the distance between the particles for K 0 in units of the period of the potential. We slightly modify (3.13), which yields Pn = X n - X n -l - u, by setting
=
Then, instead of (3.14), we obtain K X n+l
= X n + Pn+l .
(3.18)
This mapping, which is termed "standard map" or "Chirikov map" in the
N
H MN = K
L n=M 1
1 2
(1-cos27rX n ) +
(27r)
or gIven parame ers h=
lim
N-M-too
N -1 MHMN'
N
L
1
2 (Pn -
2
u)
.
(3.19)
n=M 1
e average energy per par
lC
e IS
(3.20)
3.2 The Frenkel-Kontorova Model
95
cles:
If a state is periodic relative to the lattice (a commensurate state), there are integers P and Q, with P and Q relatively prime, and xn+Q = X n + P. This leads to W=
Therefore, a commensurate state has a rational mean particle distance w. A state with an irrational w, on the other hand, does not lock in to the lattice, which affects some other h sical ro erties as well. Here as in the case of the Hofstadter butterfly, physics distinguishes between rational and irrational numbers!
Programming the mapping (3.18) is very easy. Since we are dealing with numerical manipulations, we define pi=N[Pi] in Mathematica and define the t[{x_,p_}]
= {x
+ p + k/(2 pi) Sin[2 pi x], p + k/(2 pi) Sin[2 pi x]}
The result of list [ ] is a list of nmax+l points in the x-p plane, which describes the physical state for a given set of initial values Xo and Po =
xlist[xO_,pO_] := Map[First,list[xO,pO]]
individual coordinates via Map:
96
3. Iterations
The phase-space diagram is generated with ListPlot. The energy and winding number are easily calculated from the state 111 = list [xO ,pO]:
vind[xO_:.0838,pO_]:= ( v1=xlist [xO,pO]; (v1 [[-1]] - v1 [[1]]) /nmax)
pnev = p+K/2./pi*sin(2.*pi*x); xnev = x+pnev;
time in this inner loop, where these commands are executed very frequently, but should be replaced by constants. In our program, however, the graphics
xs = fmod(xnev,1.)*xmax+10; ys = fmod(pnev,1.)*ymax+100; VIa
putpixel(xs,ys,color);
For each call, a new color is selected: color = random getmaxcolor
+1;
In this way, a display with different orbits in different colors is generated on the screen, each one representing one state.
Results
n, n
This picture is independent of the ratio
(J
of competing length scales, since
3.2 The Frenkel-Kontorova Model
97
Fig. 3.9. Orbits in the x-p plane. On the workstation, a new starting point can be selected b a mouse click and the resultin orbit is lotted in a new color
this parameter is not used in the iterated function. Each orbit has a winding number w, which depends on the starting point and the periodic potential, but not on u. The equilibrium constant u shows up only in the energy per
=
K 211"
2
»+ -21 (Pn - u)
(1 - cos (211"x n
2
(xn,Pn). Around these commensurate states, one sees closed orbits, Le., one-
dimensional ones. These states look almost the same as their commensurate relatives in the centers of the orbits but each x oscillates about the corre-
98
3. Iterations
Mod[t[t[t[t[t[{xO,pO}]]]]],1]
==
{xO,pO}
w = 0.4 and a slightly higher energy than the periodic state. Figure 3.11 shows the quasiperiodic state in configuration space. For the particle at the after Q = 5 iterations. The oscillation can be seen even better in Fig. 3.12, where the X n are plotted as a function of n. In addition to the period with ex 0 e zero- an one- Imension or i s, ig. . a so con ams s a es that fill entire areas. Such orbits jump around within the drawing window in a chaotic manner. Some orbits obviously span the entire range of x and p values. The latter is not true for small values of K. For K < K c = 0.971635 ..., there are one-dimensional orbits that traverse the entire icture horizontall socalled KAM orbits). It can be shown that chaotic orbits cannot cross the one-dimensional ones. Consequently, they are limited to a p interval between two KAM orbits. At K the last KAM orbit vanishes - narnel the one
" We are, however, not only interested in the properties of the standard map, but are also looking for the state with the lowest energy for a given
0.5 0.475 0.45
0.375
Fig. 3.10. Quasiperiodic orbit in phase space
0.35
x
3.2 The Frenkel-Kontorova Model ~
0.05
I \
0.03
,
1\
I \
I \
I ,
I \
I'
0.04
~
1\
I \
I \ I
I
.
0.02
"-
I ,
V
n
0.01
}. J
\1
If}
-.,
1 &
\\1
\I
\ 1
11
~
Fig. 3.11. The same quasi• ,.-
.
~
A
"1 ~
.or •••
. ...
L1CU
~4-~4-~ ~~ : _ ...,:_
'> 1 fl
~u~u.....
.., . . . .
VLl
~~~_:
lIV'p
VI.
&0'
till"
,.-
~,
Y
'1, -
\;L; J
• • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • •
no
V.U
.-...
99
0.6
• • • • • • • • • • • • • • • • • • • •
= >< 04
'-'
• •
• • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • •
n_ v.~
0
0
20
40
60
80
3.~A!:. Tne QlSplacement (modulo 1) of the nth partide is plotted for the same function as in Fie:s. 3.10 and ~'Ig.
X
100
3.11
n
which we will not discuss here (see, e.g., Griffiths). Figure 3.13 shows h(xo,Po) . . m a Sllce or tne Xo Po plane lOr Xo nxea at tne valUe U.UOJO ana u - ~/tJ. ~ne corresDondine: windine: numbers w can be seen in Fie:. 3.14. In the interval shown, h reaches a minimum at Po ~ 0.35. If we want to find the global minimum of the energy, we have to scan the function h(xo,Po) in the entire Xn-f)o plane. At the minimum. w appears to be "locked" into the value w = . ..1,' .. ..1,' nf h( 'r'~ ~ !:llnrl tho ~ n.A. If tho .- . , 'v'r v / number w are determined for all values of u, w(u) exhibits a fascinating behavior, which is also called the devil's staircase: w "locks" into each rational ~
.....
\
I.
•
, , W ~ U)
.
PIn ;n otono I~
•
Uc:G:5 aU
n
•
-.-
• ..l.Ll..
1.
•
.
_1
..
VI IS Lel'lS , aUU
n .
.:lIO
~
('1,
'~~U
v, .
·1"
~
",vU ..
~
&
aUY LWV ISLel'lS
• LUel-e
lIS
agaIn an mfinite number of steps. Nevertheless, w(u) is contmuousj for all irrational winding numbers there is a u value and a corresponding ground state. This behavior can be proven mathematically. The tunctlOn w{u), WhiCh resists all imagination, results trom the competition of two lengths. The commensurate ground states belonging to the rational values of w correspond to individual points in the x-p plane, while it can be shown that the incommensurate ground states do not correspond to area-coverin2' chaotic orbits' rather thev corresDond exdusivelv to lines. As a o~..:In .,.,.,.,,+n ~&~ .....
•
&&'V'uv,
without changing their energy.
.J
" .... .,.,. 1.. n ...1.
v"-"&&
",v
~~
+1..n U&&V
.
.-
••1
100
3. Iterations
•
f\ f\')O
0.028 >. tlO
•
•
0.027 •
~ o 0.026
• • • • • • • •
0.025
•
• • •
U.U:l4
-
u.~
• •
U •.J
U.~.J
_.
• • • U ...
U •.J.J
pO
-!3 tlO
.5
:a
~
0.45
• •
0.425 nA v.
.5 0.375 ~
O).~O).
•
0.475 ~
Ig.
• •
f\,
.... 0
~
£Jnergy 01 a lOree-nee state wltn u 0.4 and initial value Xo = 0.0838 as a function of po ~
•
0.35 0.325
•
•
_. -
•
•
0.2
0.25
~
0.3
0.35
11::).
..
, ,
Ul:S-
O).~
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
1 = (w (t)) 2 + N2 w (t) . z v + N2
(z v )
2
N'
Note that (zv)2
= Lj
Z~j
= N. Iteration of (3.34) from 0 to t, using w(O) =
(w (t) . W*)2
(3.38)
(3.39)
or (3.40)
3. Iterations
110
,
,
classified correctly. Thus, the perceptron rule can actually learn all learnable problems perfectly.
(with probability 1) for M < 2N. After the learning phase, the perceptron can generalize. This means that
where the average is taken over many inputs S. The value 9 = 1/2 is the result of random guesses and the perceptron can not generalize in this case. For 9 > 1/2, on the other hand, the perceptron has recognized a certain re ularit in the exam les learned and has a robabilit of a reein with
" We now want to use the perceptron for the purpose of time series analysis and make predictions for the next step. We assume we have a sequence of
F
= (1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1, -1, ...)
(3.42)
In each step, the perceptron probes a window of N bits,
and makes a prediction for the bit Fv+N: FV+N = sign (w· xv) .
(3.44)
Then the erce tron earns the exam e Xv F v N accor in to t e Rosenblatt rule (3.32), shifts the window to the right by one bit, and makes a new prediction for the input F v+N+l. This is repeated and a hit frequency 9 is determined.
, sequence, on the other hand, will always give a hit frequency of 9
= 50%.
3.4 Neural Networks
111
Algorithm
1. Read input:
2. Calculate the potential: for (h=O., i=Oj i 0) correct++j
4. Learn: if (h*in ut < 0) for (i=Oj i",j+l n
..L
,>",j-l n
(dx)3
",j-2\ n I
.
(4.60)
Investie:ate the stability of this ale:orithm by usine: the ansatz (4.49) in , , tn (L1 ~7\ thiCl lO!llrlCl tn tho ,. , (L1 I{O\ th!llt , , .. , ..... T"\
-J
.~
~
-
. 1 2idt [sin (2kdx) - 2 sin (kdx)] a=-(dx)3 a
.
NumerIcally determme the maxImum J.L of I sm{2kdx) - 2 sm{kdx)I {p, ~ 2.6), and show that, in combination with the requirement lal < 1, this yields the stability condition dt
1
~
< - (dx)" . p,
(4.61 )
144
4. Differential Equations
, mine the stability limit with respect to dt, for a given dx; i.e., approximately determine the maximum dt allowed as a function of dx. Confirm
Literature
,
,
Crandall R.E. (1991) Mathematica for the Sciences. Addison-Wesley, Redwood City, CA
4.5 Time-dependent Schrodinger Equation its motion is
, back and forth regularly. This classical picture, which is based on the idea of a pointlike mass with precisely defined position and momentum, no longer
that the stationary states in this case are standing waves. But what happens to an initially localized wave packet that moves towards the walls of the box?
v w v p isperses, and wild interference patterns arise from which smooth wave packets suddenly reemerge. Finally, the entire process repeats periodically with time.
Ph sics
, which moves in one dimension in a potential V(x). Then 11/J(x, t)1 2 dx is the
4.5 Time-dependent Schrodinger Equation
145
, coordinate representation:
In order to put this equation into a dimensionless form, we normalize the time by to and the position by Xo:
Now we choose to and Xo such that the following equation holds: !it = 2mx 2
•
tIme
III
umts
0
H is the normalized Hamiltonian of the particle. There are two ways to numerically solve this equation. First, we can calculate the eigenstates and eigenvalues of the stationary equation Htf; = Etf;, expand tf;(x, 0) in terms of the e a h .f ri r it. w can directly integrate the time-dependent equation as shown in the previous section. The second method can even be used for problems for which the first one fails which is wh we want to describe that method in the al orithm
Here, the coordinate x is expressed in units of the box's width a, and the energy E in units of !i2/2ma 2 . The energies En of the stationary states tf;n (X) are known from the uantum mechanics course: n
tf;n (x)
=n
1r ,
were
= { y'2 c?s (nITx) y'2 sm (n1rx)
for n odd _1 < x < ! . for n even' 2 - 2
(4.67)
146
4. Differential Equations
so for 1j;(x, t) we obtain 00
C2m-1
exp
m=1 00
+L
C2m exp -i1r 2 (2m)2 t sin (2m1l"x)
(4.68)
m=1
,
, 2
of the energies En. Each frequency W n = n 11"2 is an integer multiple of the fundamental frequency WI = 11"2. From this it follows that 1j;(x, t) is a periodic
.
.
, entirely returns to its initial state 1j;(x, 0). We will see in the results section that simple patterns emerge even at
1j; (x, ~) = -1j;e (x, 0) + 1/;0 (x, 0) = -1j;e (-x, 0) -1j;0 (-x, 0) = -1j; (-x, 0)
(4.70)
If we insert the result from (4.70) here, we immediately get
the complex interference patterns. The results section shows, however, that
4.5 Time-dependent Schrodinger Equation
147
a consequence of the initial condition we have chosen, 2
The function 'l/J is a Gaussian of width (J, which is concentrated near x = -1 4, multiplied by exp(ikx). Owing to this factor, the particle has an initial
(4.74)
'l/J (x,
I) = -i'l/Je (x, 0) + 'l/Jo (x, 0)
(4.75)
.
(4.76)
cos kx sin kx ,
i.e., a term which for
(J
=.0.05 is of the. order exp(-25). The remainder can
= 21 [ I'l/Je (x, 0) + 'l/Jo (x, 0)1 2+ I'l/Je (x, 0) -
'l/Jo (x, 0)1
2]
In summar we obtain (4.78)
148
4. Differential Equations
j (x,
I) '" ~j (x,O) -
~j (-x,O)
,
(4.79)
At even shorter times, waves with a simple structure arise as well. If we set t = Tp/q with integers p and q which are relatively prime, the phase
, x, IS a superposItIOn 0 q waves, eac 0 w lC IS an III mte parba sum out of that same expansion for "p(x,O). If we assume that each partial wave is a smooth function, then their superposition is smooth as well and "p(x, t) exhibits a simple structure at those times. This is precisely what we will s r whe we do the numerical inte r tio . With this we conclude the analytic considerations and turn our attention to the description of the numerical integration of the time-dependent Schrodin er e uation. Algorithm First, "p(x, t) is discretized:
Here, j and n are integers, and dx and dt are the step sizes of the space and time coordinates. As before, we write the second derivative as
with an error of the order O(dx 2 ). Now we can discretize the time deriva. . IV, n y 1 V however, does not conserve the overall probability "p x, t dx = 1, which is not allowed to change with time. It is indeed possible to find a discrete approximation of the partial differential equation that conserves the overall robabilit. To this end the discretized time evolution 0 erator must be The solution of the Schrodinger equation (4.65) can also be written in the form
The approximation
e- iHdt ~ (1 - iHdt) correspon hand, with
W lC
+0
dt 2
,
(4.83)
4.5 Time-dependent Schrodinger Equation
149
(4.87) With this, (4.86) yields .2 (dx)2
i-I _ n+l -
We have abbreviated the second line which onl contains terms referrin to the time step n, by {}~. This equation has the form T1/Jn+l
= nn ,
(4.89)
with a tridia onal matri this. We use the ansatz "/,i+ 1
_ If''n+l -
1/J~+1 =
i "I,i
a
If''n+l
+ tr1.1n
(4.90)
.
-1
2
2 + (dx)2 Vi - i (dx)2 - ai
solve for ai and ~. The result is
1/J~+i + ~ - {}~
(4.91)
150
4. Differential Equations
.
.
~ = f}~
+
iJ!.-1
;-1 .
(4.92)
lated from the wave function tP~. To solve these equations, we need the initial state tP~ and boundary conditions. Since we want to confine the particle in a
.
. ..
.
where we have redefined the boundary as x = 0 and x = 1, as this is easier to program. The number of grid points, J, is thus fixed at J = 1 + l/dx. At
2
tPn+l
+
(.
1
2 (dx)
dt
2
- (dx
)2
1
)
1
_
1
V - 2 tPn+l - f}n .
(4.94)
(4.95)
Since the boundary value on the right, tP~+1 = 0, is fixed, this allows the calculation of the entire vector tP~+1 at the time step n + 1.
..
.
1. Choose an initial state tPb and use it to calculate f}~ according to (4.88). 2. Calculate the vector aj from the initial value given in (4.95) and the recursion formula (4.92) . . For all ositions· calculate the variable b!. usin the initial value from
4. Use (4.96) to calculate the values of the wave function ~+1 for the next time step, using the initial value tP~+1 = o. This also yields {}~+1
As mentioned before, we define the initial state as a Gaussian wave packet that moves with a mean momentum k:
4.5 Time-dependent Schrodinger Equation
,
"
n ,
151
,
{~} are complex numbers. Whereas Mathematica, as well as other languages
like Fortran, can deal with those numbers directly, in C one has either to
typedef struct{double real, imag; } complex;
(4.98)
can be found in the function calculate_b which performs the iteration of
{
int j
double a2;
b 1 .real=omega 1 .real; b[l].imag=omega[l].imag; for (j=2;jx+c) {s=y-(x+c); c=O;} else {s=y-(x+c)-18; c=1;} x=y; y=z; z=s; n=69069*n+1013904243; return (z+n); }
maine) { ...:a~ .. l.'~
,
- _., _-1\
•
.&o"'"fJ .&oJ
for (i=O;i Rk). whether it has reached a site adjacent to the aggregate. or whether !ll
.
ClhArt •
(fl ./ \'
~~-
fl ,\
Ar
.
,1
lAnl1" " •
!ll
·U/
'0
u
" £
(J:/ \.
'> fl.\ ·U/
-'I
tA h.o
performed in the next step. These four "ifs" in step 3 of the algorithm above are tested by the function check () : char checkO .f
double rtxty; x=rx; y=ry; ... - ..'1.....
._, LL
.
.. J ,
,A'"A'
-, t
"J'
~~.
,
.
A t if (r >= rd) return 'c'; if (xf[rx + 1 + lmax/2][ry + xf[rx - 1 + lmax/2][ry + xf[rx + lmax/2][ry + 1 + xf[rx + lmax/2] [rv - 1 + return ' a' ; else return t j , ; \.L~
."-
,~
,
... "" ........ u
lmax/2] lmax/2] lmax/2] Imax/2]
+ + + > 0)
Imax is the size of the drawing window. The following function adds the
particle to the aggregate: void aggregate 0 {
double xty; xf[rx+lmax/2] [ry+lmax/2] =1; x=rx;y=ry; .\ \ . - ............,I, ............... t "'1'"...... I., ...r '... • .1 .1" t .., .. , _ ... .~,
~
.L'"
___.
In ... £.OJ. I
~t'
... .LD"'" \
"
It;:)
.,
"Ut""'" t J
circle(4*rx+340 t 4*ry+240 t 2); }
J:lor the cIrcle jump, a random vector of lenKth 1t -lts IS added to the posItIOn • _1
of t.hp ~
•
170
5. Monte Carlo Simulations
double r,x,y,phi; phi=(double)rand()/RAND_MAX*2.*pi; x=rx; y=ry; r=sqrt(x*x+y*y); rx+=(r-rs)*sin( hi); ry+=(r-rs)*cos(phi); }
if(kbhit(» stop=1; svitch (check 0 ) {
case case case case
;break;
}
Result
square lattice
5.3 Percolation
171
Additionally the simulations show that, thanks to the introduction of the long jumps for R > Rd, the processing time does not increase significantly if
Exercises
complete yet. While the "arms" of the cluster continue to form, additional particles can still reach its interior regions. By arbitrarily stopping the sim-
Varying the model parameters. It is interesting to observe in which way the form and fractal dimension of the cluster chan e if the ori inal DLA Introduce an additional parameter Pstick into the program dla. C, which represents the probability that a particle which arrives at a site adjacent to
Literature
MA Sander E., Sander L.M., Ziff R.M. (1994) Fractals and Fractal Correlations.
5.3 Percolation
, case we can use Fourier transformations to describe the periodic structures as
172
5. Monte Carlo Simulations
, to understand materials with irregular structures as well. There is a model for disordered materials, which permits a rather sim-
the A atoms are magnetic, with a short-range magnetic interaction which is only effective if two A atoms are located next to one another. If there
clusters of A atoms will increase as well until, starting at a threshold value Pc, a cluster extends through the entire crystal. The value Pc is called the
two opposite sides exists.
5.3 Percolation
.
173
.
Pc or 1 eren lattice structures and cluster definitions? How does the average size of the finite clusters increase as P is increased up to the threshold Pc? How does the 1
V,
U
0
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 0) permits uphill steps as well, with a probability that depends on the difference
As in the previous section, this time can be estimated by using Arrhenius' law. Let .dE > 0 be the difference in altitude to be scaled. Then a typical
5.6 The Traveling Salesman Problem
203
for the simulation - here, t is the actual processing time - should fulfill the inequality
if possible. Therefore, as a function of time the temperature T may only
w v ,
r
optimization algorithms, which work with populations of paths. Before we discuss the details of the algorithm, we want to estimate the
i=l
For N -+ 00, the right-hand side can be written as N(r), where (r) is the average IS ance e ween nearest nelg ors. e now wan 0 ca cu a e r, neglecting boundary effects; to this end we consider a sufficiently large section of the plane, in which cities are distributed with a density p = N / L 2 • Let w(r)dr be the probability that the nearest neighbor has a distance between r and r dr. In other w s r r i th fin i r
, the circular ring with the area 27rrdr: r
w r dr =
1-
27rrdr . o
This integral equation for w(r) can immediately be transformed into a dif.
resu ts
r
III
If = -27rpr I
with
1(0) = 1 .
(5.74)
204
5. Monte Carlo Simulations
f (r) = e- 1rpr
and
w (r) = 21rpre- 1rpr
(5.75)
The average distance between nearest neighbors can be calculated using w(r): 00
(r) =
rw (r) dr = 21rp
(5.76)
o
1
Eo> -LVii. -2
(5.77)
can only be determined numerically; for example, Percus and Martin find e= 0.7120 ± 0.0002 in the limit N --t 00.
Algorithm
(5.79) ways of turning a round trip S into a slightly changed path S'. For the sake of simplicity, we will only present the following one: we randomly select a
.
S' = (i 1 , ... , i p -
1,
ip+l, ip+I- 1, ... ,ip, ip+I+ 1," ., iN)
.
(5.80)
ber r E [0,1] is less than the Boltzmann factor exp [- (H(S') - H(S))
IT].
5.6 The Traveling Salesman Problem 2
205
2
3
6
6 4
4
randomly distributed in a square of size L. The array map of structures city is used to store the coordinates (x, y) of each city: t edef struct int x city map[MAXCITIES];
.
N is set to 100, but alternatively it can be passed as a parameter when calling
{
if(argc>l) N=atoi(argv[l]); }
The order in which the cities are visited is stored in the array int path [N] .
llhile (! done) anneal(path)i if(count++ > DRAW) {
206
5. Monte Carlo Simulations
}
The function event () examines the keyboard buffer. While the program
r
uce e p eng The function anneal (path) calculates the next. Monte Carlo step. The position pos and length len which are needed in order to generate the new
,
,
if the difference de of the two path lengths obeys the condition II
If this expression is true, Le., has the value 1, the move S --+ S' is accepted and the standard function memcpy is used to copy the new path to the memory
{
double newlength,de,lscal; int pos,len,newpath[MAXCITIES]; pos=randO*fl; len=rand 0 *f2 ; change(newpath,oldpath,pos,len);
if«ann==l && (de < 0 I I frand() < exp(-de/temp») I I (ann==O && de < temp» {
number generator which generates real numbers distributed uniformly in the
5.6 The Traveling Salesman Problem l1n;f •
Tf "",n ho ~1
.1
~1 ",f fho
.1".
.
1. ~
Af
fho
~
r
'0'
-,
207 .1
fA1" A
V li:L
#define frandO (double)rand()/(RAND_MAX+1.)
Tne new patn IS generateo oy nrst copymg tne 010 patn toP) to tne new one (np). Then the order of the cities between pos and pos+len is reversed. The code for this is ....... .,; ...I
- 'L
.....
r
( .,; _+ '
_ .... rl °r" J
.,; _+ '
......... rl -r" J
.,; _+ '
,
............ .,; _+ 1 .._' -, r
.
L
.LUI.
.L'J.
memcpy(np,op,N*sizeof(int»; j=len; for(i-O;i 0, PrependTo[list,O]]; Plot[f[x]J~x,O,list[[-l]]+l~];
list ] ~~
- -
'L
-m
r":t
"
41
--4
.
PInt nf
T.'
.T.,-,( , and a IiJlt nf . thp ..fir.flt ..fn'll.r 7.prn.fI nf..
J3 (x) . ........ ,1
T 'I;
-~.-
,.~
-"
Do[Print[R Hello World Rl,{20}l screen ~u umes.
~
Writes Hello World to the
219
A. First Steps with Mathematica
.
T.nnnQ· -
Do [expr, {iterator}] For [start, test, 1ncr, body]
.L----' ...
...... ..
.
..!I.
'L
_.
_.I
Nest [2:, expr, nl NestList[f, expr, n] FixedPoint[f, expr]
... -
•
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
the numbers from 1 to 10 and their squares. ... r 1 • • ~ n A.\ .= I . = -- . ~ n"., tAnll'; , .. r'" . 'D ....;n.. r.11 tween 0 and 0.8.
,1 ;all
~
lienerates
..
-
---
&.
Nest [Sin, t, 3]
-
.
~.~,
..
•
n.:;
~UJ
.J
.(n'l,r
hp-
'L
Sin[Sin[Sin[t]]]
~
- ---
I'• • D'- LD;LU,
-J
• , uu"
In",
I
1;"t:1(""t:Ur ,.)v
•
UruUr
W1;",,, • ,I
,I
•
•
I
,,"'t:
value 1.5. NestList[Sin, 1.5, 30] I
I
.j".,
thp
.
n( -
numerical value of cos x to 18 digits.
f[x_]:= N[Cos[x],18] FixedPoint[f,1/10] II
\.-U;:);L,
I'
I'
NestList [ .. ] yields a list of all values cal-
thp .
~ ,
li.e;., ",.e;;L JUI
\.-U;:);L
0.739085133215160642, the fixed point of
.
;L c,u
rr
.
~l.IIJJ
......... l.II, ...... y.
If [Random[] < 0.5, Print [Onumber < 0.5°]] beep: = Print [11\007 11 ] ~I:L.Ka
LJ <
.~,
;
beepbeep:=(beep;Pause[l];beep)
Deep, DeepDeepJ
theta[x_]:= If[x Automatic]
Differentiation, Integration, Taylor Series \,;~ear
L _..,...a~
*.0 J
D[Exp[x"2], x]
~
the derivative of exp(x2 ) with respect to x.
220
A. First Steps with Mathematica
Simplify [D [%, x] ] ---+ the integrand of the above integral. The function Simplify [ .. ] reduces fractions to their least common denominator and tries
to put the result into the simplest possible form.
---+ t e e nzte zntegra
0
e
integration with Nlntegrate [ .. ] . A doue imits
Head [series]
---+ SeriesData, a Mathematica object in its own right,
not a polynomial.
Timing[Series[Exp[Sin[x]], {x,O,80}];] Null}
---+ {11.54 Second,
Vectors, Matrices, Eigenvalues
r
= Table[x[i],{i,3}]
Matrixl'orm[b]
---+ {x [1], x [2], x [3]}
---+ the matrix b
IdentityMatrix [3]
.
---+ the 3 x 3 unit matrix.
A. -.....
,
yieLas me transpose OJ __
'L
r ..... ' L-"
............
T.
r
221
First Steps with M athematica
1.
1.
... "oJ
"..,
.,
......
r'L ,
..
T.
LLlJ
D •
Det[b]
--+ the determinant of b .
voor
---t
boov
--+ the matrix b applied to the vector v .
bood
--+ the matrix product b times d .
me scaLar proauct OJ v ana r.
booJ:nverSe[b) the matrix b .
--+ the un'tt matnx; Inverse LbJ Y'telas the 'tnverse of
Eigenvalues [b) "'t:'
'V~
VJ
..1
il.·
L
....
--+ the eigenvalues of the matrix b . They are the . J.
..1
"n", .... -v, u£:-,
I:
'
J
'07
,
I I .il.
.1. '.1.
,-,un
.J
. J .i
• l
r J.
J
U/"",,,
bin;
l;araano formUla.
nb = N[b]
.-
--+ the numerical approximation of the matrix b . The exact .1.
.J
...
nrp
~
. J
h'l'
J
..1
r,.,'h 1 ~ [() A7f\11Fi. of the eigenvalues of the matrix nb .
'III';
-
., "Aa
u = Eigenvectors[nb]
., ()()I'\L!A,.,. ...
nf 10- 16
"
')l
J,j "f
n
~
--+ a list of the eigenvectors of nb .
-\oLJ--J
-.- L
'I1l9.th nn
() 04()Q()4Q , ()
l
_. -\oLoo ..
.1.
oJ
'. ""u", fJoAI,
• J
L
"7
",n::.
I."""""
,.
~J.
".",(..c; "16C;.,
'"
uJ
nb are orthonormal, except for numerical inaccuracies of the order 10- 16 .
Sort[Thread[Eigensystem[nb]]] J
~
tn thp ~~~ .,
J.
oJ
oJ
--+ eigenvalues and associated .J~ nf thp.
,':-1-
.,
"
.J.
'DC>
Solving Equations
FindRoot[Cos[x]==x,{x,l}] --+ {x - > o. 739085}, the solution of the equation cos x = x. The brackets {x, 1} mean: seek a solution with respect to x and start the search at x= 1. F1ndRoot [i Cos [a*x] ==x, -a*Sin [a*x] ==-1}, ix, 1}, i a, 1 t] Systems of equations can also be solved with FindRoot [ .. ] . Plot[Zeta[x]-2,{x,loo2,3}] "'t:'1
v .",
~'"16t:' , U",!/t:'
~
'~
--+ a smooth function which has a
...."flU'''.
FindRoot[zeta[x]-2==O,{x,2}] --+ an error message because the function cannot be differentiated symbolically. F1ndRoot[Zeta[x]-2==O,ix,i1oo2,3}}] Th.9.(l
J
Tf nnp "
-
..
• r-
-"
n .(ltnrl .
variant of the secant method is used.
~
_J
•
.J
nf nn
"
•
'. J
.1A ~
n
A. First Steps with Mathematica
222
.....
...!!II-
.&.
_...
'I ...
•
L ...... g
60
--
r.
1.-'
......g ,
.ft. 1
•
J:!.
.
..J.
u.uuo
_VfJ
.
1
.1
Solve [eqns, vars] tries to find exact solutions. NSolve[eqns, vars] numerical solutions of algebraic equations. 'I'
--- -..--, -.... ,.. -
.I .
,, ___ r_ '"'
...... '"
1
,..~
......,.. 'V... " ....'V "'J "''''V''''''''''''
-.......-
..
....
l..
DSolve[eqn, y[x], x] solves differential equations. NDSolve [eqns, Y, {x, XIIl1D, xmax}] finds numerical solutions of differential equations.
.
Solve[a*x~2+b*x+c==0,x]
the 2 solutions of the quadratic equa-
~
tion.
--* {{x -> Sin[a]}}
Solve [ArcSiD[x] ==a,x] A
A
Solve[x S-Sx 2+1 == 0, x] NSolverx~S-Sx~2+1 ~.t .f.J.':A
VJ
.~.
", ...... ""1
Too difficult.
-= O. xl
.
5 numerical values for the zeros
~
DSolve[y"[x]==y[x], y[x], xl differential equation.
~
D::iOJ.veLY'LXj==\;OSLX*YLXjj, YLXj, Xj
the general solution of this ~~
lV 0
success.
NDSolve[{Y'[xl==Cos[x*y[xll,y[Ol==O},y[xl,{x,-S,S}l a Mathematica obiect called InteroolatinfzFunction .
~
rX..l = vrxl /. % This is the format that is used to convert the object InterpolatingFunction to a normal function which can be plotted with f
Plot[f[x],{x,-5,5}]
Patterns, Ordering, Sorting Remove L"GJ.ODaJ. * .• j -
~1St
t~,
;&, :l:la), golD), x D, :l:LDJ,
PositioD[list, f [_] ] . ,1 . fr
~
:J.", 51nLPJ
;&}
{{3}, {6}}, a list of all positions with
"
~
~
Cases [list, _~ 2]
~
Count [list, _~ -l
~
n.1 . . . .,..• • • • r1.; ... "
r .... ,
.1.' oJ
616
LLI.J
all cases with the exponent 2.
2, the number of all cases with any exponent.
rhll .
Ull respectively. The output of a
C. First Steps with Unix
239
The Standard Editor vi
consortium, is used frequently as well. Here we just want to discuss vi, since it comes as part of every Unix system.
•
• At startup, the editor is in command mode. This means that the keyboard in uts are inter reted as commands. 1m ortant vi commands in this mode A
Jumps to the end of the line and switches to insert mode (Append)
i
Switches to insert mode (Insert)
Esc
Switches back from insert mode to command mode
x
Deletes the character at the cursor position
dw
Deletes one word
G
Jumps to the last line
/ pattern Searches for pattern
240
:x
C. First Steps with Unix
Saves the document and leaves the editor (Exit)
:q :q !
Leaves the editor, discarding changes (Quit)
:w
Saves the document (Write)
Reads the file called file (Read) : set nu Switches on line numbering (Set Numbers)
, of text and copy them, or indent entire blocks. The C Com Her The translation of a C program into executable code is done in two steps. In the first step the program is translated (or compiled) into an object file. The h m i r executable program. The C compiler which comes with a Unix system is called cc. With the
-0
Optimizes the code
path -Ix
The linker links the library Iibx to the program
is
c.
First Steps with Unix
241
In order to compile larger program packages, the auxiliary program make is often used. It reads a file called Makef ile and processes the instructions given wi . there. Networks sec IOn we WI network. Every computer connected to the Internet has an address. This address consists of four numbers, each of which can vary between 0 and 255. Every address has a name associated with it. ft . h sik. uni-wuerzbur . de for example, currently has the address 132.187.40.15. The individual groups of numbers cannot be mapped to the components of the name in a unique way. For exam Ie an address at the Universit of Wiirzbur . uni-wuerzbur . de IS
one should use the names whenever possible. onnectIons to
The command telnet computer can be used to establish a connection to another computer on the Internet. Here computer can be either the computer's name or 1 s n erne a ress. output if there is a physical connection and our computer is running: Trying ...
(some machine-specific informations)
10 in:
At this point, the user has to enter his or her username and password. One should always close telnet sessions correctly, i.e., leave the computer via logout. If nothing else works, one can get to a telnet menu by using the esca e character that is s ecified. The s mbol ...] used here means that the CONTROL key and] have to be pressed simultaneously. Once in the telnet menu, one can get short instructions via the command ? The connection can be terminated with the command close.
changed explicitly by the option -1.
C. First Steps with Unix
242
.
r"' &- . ,
I" &&v&&&
'W'
&&&6
.&.
&
co·
r't..L1.
r"'
-r
""
In order to exchange files between computers there is FTP, a file transfer protocol. A connection is established via ftp computer. Again, computer can 1..
•. 1..
T
U1V
,
,
TT
a.
V.l
GU.
• .I..I.C.lC, IIVU,
a.
, . ,
• to
.y
Ul)Cl lldl) IIU
••
111.11.1-
or hersell; the computer asks tor username and password. Alter a successful login the following commands can be used, among others: to
sP.ts thp.
hi
_.:~"I.. ~ •• 4-
.'
.:I
to
1.. ~
Lp.. t.hp n~.t.~. ~.rp
to
,
' ~
as
sets the transfer mode to ASCII (text mode). In this mode, control characters may be suppressed. There may also be a svstem-denendent conversion of the characters
Is
lists the files in the remote directory (list)
cd dir
changes the remote directory to dir
tzet file
copies the file file from the remote computer to the local one
put file
copIes the file file from the local computer to the remote one
mget files similar to get, but this command accepts wildcard characters in t.hp filp
~mr1
, . • filpQ
to
&
mput files similar to put, but this command accepts wildcard characters
in the file name and transfers multiple files
-
.. -.LranSler .lnt;ernet; -~ ue ~
Many institutions offer programs which anyone may copy freely. These can be obtained through the Internet, using FTP. To this end, special FTP servers . olIer tne option or logging in unaer tne username I'&P or anonymous. ~ ne password required is one's own e-mail address. For example, the programs described in this book are available from the FTP server . .,. .:. .g._z. ~
A
..:II .
-vr·r&&J---·~-
,
TT'1o
,,
.. nn .. n ... ~n ..... ,
\ l;Ullt:l.lL .I.e
•
.I."~ • .I.0'
•
,.
"
.
PlotLabel->"Discrete Fourier transformation", PlotStyle -> Thickness[O.O], DisplayFunction -> Identity];
Show[gl,g2,
)
251
252
E. Program Listings
{s,64}]//N plot4:=Plot[{Re[fapp1[t]],f[t]},{t,-5,5}] fapp2[t_]=Sum[N[fslist[[s]]* +
onJugate Exp[-2 Pi lot5:=Plot[{Re[fa
2 t
1.4 Smoothing of Data: smooth.m Print[ll\n Smoothing Data by a Convolution \n"]
,
,
SetOptions[ListPlot,Frame->True] SetOptions[Plot,Frame->True,RotateLabel->True] plot1 := p1 = ListPlot[Thread[Join[{xdata},{data}]], PlotSt le->PointSize[.01]] sigma= 0.4 kernel = Table[ N[ Exp[-x-2/(2*sigma-2)]],{x,-5,5,10./255} ] kernel = RotateLeft[kernel,127]
smooth=Sqrt[256] InverseFourier[Fourier[data] Fourier[kernel]] smooth=smooth//Chop lot3:= 3=ListPlot[Thread[Join[{xdata},{smooth}]]] plot4:=p4=Plot[BesseIJ[1,x],{x,0,10},PlotStyle ->Thickness[0.001]] plot5:= (If[Head[p1]==Symbol,plot1];If[Head[p3]==Symbol,plot3];
1.5 Nonlinear Fit: chi2.m
plot1:= (gr1 = ListPlot[data,PlotStyle -> PointSize[0.02], DisplayFunction -> Identity]; gr2 = Plot[Sin[t] Exp[-t/10.],{t,0,3Pi},
.
.
f[t_]=a Sin[om t + phi] Exp[-t b]
.
E. Program Listings
-
_..
r. -" r.
."_-.TT.
_
~
-
~'i.l."
L....
':. _
&.
" t . " , \oJ,
t ...... t
&.~
• &.
I I
A ."
square[{t_ty_}]=(y-f[t])-2/sigma2 chi2=Apply[Plus t Map[square t data]] find:=FindMinimum[chi2t{atO.9}t{omt1.1}t{phitO.1}t{bt.2}] fit:=If[$VersionNumber>=3. t BestFitParameters I. NonlinearRegress[datatf[t]ttt {{a t 1.1}t{om t 1.1}t{phi t .1}t{b t .2}}t ShowProgress->True]t N"... 1 .
·... i ...
rit ....... .,r... 1 ...
II_
1
11.
I __
1
;1. .f_l.":
,,1.1.
t,";..- t . 11. t .fl.. .. , t' t - •• _ ... '0' ' ........... oJoJ pvalue[x_]=1.-CDF[ChiSquareDistribution[7]t x] interval={Quantile[ChiSquareDistribution[7]t. 05]t Quantile[ChiSquareDistribution[7]t.95]} limlx_J=QuantilelChiSquareDistributionl4Jt xJ plot2:=Plot[PDF[ChiSquareDistribution[7] tX] t{x t Ot 20}]
:''L.. -t:.
-~
t ... -t -.:
-
-~
-~
.~ ~
rule = If[$VersionNumber>=3. t
... .....
1
..... r ....
~
P1n...Pn; ...... phiO t om->omO}t {a t .4 t l.3}t{b t -.04 t .2}t ContourShading->False t Contours->{chi2min+lim[.683]tchi2min+lim[.9]}t -.T
.,
A
r-- -'
......
....- t - .
11. I __ -~
-~
-~
~ ~
• ...hA1 -~~" .. " "h"'\.1
_n, _v_r ..... " I ...y,u... I .. 1.· ~ ' . ' n ....._,u ................ 'y,u"'-t'" ............"l- t {om t .90 t 1.05}t{b t O.O t .15}t ContourShading->False t Contours->{chi2min+lim[.683]tchi2min+lim[.9]}t
_'"
~
PlotPoints->50tFrameLabel->t"om"t"b"~J
g[t_]= f[t]/.rule I step:=(data2=N[Table[{ttg[t] + .4 Random[]-.2}t ~ p;lll· ~1: n ~P; T-f:
_.
r~"
-
~.
____ A
-
__ •
=~
.
_. r.. t-4=r.., .. -.. t .. t {{ataO}t{omtomO}t{phitphiO}t{btbO}}]t
________
I
I
•
1.1 __ ''':
"
~."
NonlinearFit[data2 t f[t]ttt {{ataO}t{omtomO}t{phitphiO}t{btbO}}]] ) tab:= tab = Tab.leLtch12tatbtOmtph1J"!.stepttlUUJ"J abtab := MaplTakel#t{2 t 3}J"ttab] plot5:= ListPlot[abtab t PlotRange->{{.4 t l.2}t{-O.045 t .2}}t AspectRatio -> 1 t Frame -> True t FrameLabel ->{"a" "b"l Axes -> None AlA _> Pn;"''''~;''ArO 01511 Pl ~
"
253
E. Program Listings
254 ..
'1\ Jr. . . .
D
..... v
...
..
. ..
.., -.:-
.
..
-
.1 _
...
..........
Print[lI\n Multipoles for a Static Potential \n II] SeedRandom[1234S67S9] rpoint:={2Random[]-1.2Random[]-1.0} Do[r[i]=rpoint.{i.10}] p1=Graphics[Table[Line[{Drop[r[i].-1]-{0.OS.0}. Drop[r[i].-l]+{O.OS.O}}].{i.S}]] p2=Graphics[Table[Line[{Drop[r[i].-1]+{0.0.OS}. n....nnr.... r;1 -ll-rn n nR~~1 r; c;~11 ' ..: __ r... _~,_rT.; __ rIn...._:r.... r';.L1:1 _11_fn "'-.... no n"\.· .. 1"'"
L ..... ' ' .......
-~
-~~....
....
r. r.·
'r"-
.~
..,
L ... - ....J
.
.~
J' ....
•
r,..
'J
•
Aft A''''
r·
.J-.-~v.vu.v.T.T.J .1. ....
.... , ..
V.T.J ..
p4=Graphics[{Thickness[0.001]. Table[Circle[Drop[r[i]. -1]. 0.1]. {i .10}]}] SetOptions[ListPlot.Frame->True] SetOptions[Plot.Frame->True.RotateLabel->True] plot1:=Show[p1. p2. p3. p4. Frame ->True. AspectRatio -> Automatic. PlotRange -> {{-2. 2}. {-2. 2}}. _'L .... 1 _,- Illy" II .. II "\.1 oJ -
9
•
~
..
..
r
-
., ,
r,
U.l.D"L.I.-_.D_"I-~''''
0 ' . , ...
J~
."
O'.J
pot[rh_]:=Sum[ l/dist[rh.r[i]]-l/dist[rh.r[i+S]] .{i.S}] plot2:=Plot3D[pot[{X.Y.0}] .{x.-2.2}.{y.-2.2}, AxesLabel->{l x l,l y ","Phi"}, PlotRange -> {-S,S}. PlotPoints->40] plot3:=ContourPlot [pot [{x,y,O}] .{x,-2,2},{y,-2,2}, n1_+n.. . .; ... +C!_~4n ,.. ... ~_ ..: ....'CO_1 __ , Ay__ T _~_, _ .... IlIyll
_.
~
",
II •• II"\. ,
J
1
J
quadrupole[r_]:=Table[3 r[[k]] r[[l]] - If[k==l,r.r,O], {k,3},{1,3}] qsum=Sum[quadrupole[r[i]]-quadrupole[r[i+S]],{i,S}] magnitude[r_]=Sqrtlr.rJ dipole=Sum[r[i]-r[i+S],{i,S}] pot1[r_] = dipole.r/magnitude[r]-3 pot2[r_] = pot1[r] + 1/2/magnitude[r]-S * r.qsum.r .......+'h=I t::. •• n"\. r, .... A. _n~~-= r.r __ ... ~ r. ......1 ....,..+'lr.......+'h1 ....,..+r.......+'h1"\. I •• _') 'l"\. r
.&
...~ " l "
~
-
...
,...
.................'r,
-~
'r
-~
'J
•
--.o;rT
'T
"'-'T
FrameLabel -> {1{.6,y.0}1,lpotential"}, PlotStyle -> {Dashing[{.01 •. 01}], Dashing[{.03,.03}],Dashing[{1.0,0}]}] Needs["Graphics"PlotField II] efield=-{D[pot[{x,y.O}],x],D[pot[{x,y.O}],y]} direct ion=ef ield/magnitude [efield] n1nT~·=P1·· ....1i1ril; '1 on ..(x ·10 10)...fv -10 10). P1 .... -~~nl ~
E. Program Listings 1.
Print [1I\n Line Integrals \n ll ] rl={Cos[2Pi t],Sin[2Pi t],t} r2={1,O,t} va ua e r , , DisplayFunction->Identity] p2:=ParametricPlot3D[Evaluate[r2],{t,O,1}, Dis layFunction->Identit ] 3:=ParametricPlot3D[Evaluate[r3] {t 1} D's la Funct'o -> plotl:=Show[pl,p2,p3,PlotLabel->1I Line integrals ll , AxesLabel->{lI x ll,lI y ll,lI z ll}, DisplayFunction->$DisplayFunction]
°
v [r_] :=D [r, t] int[r_]:=Integrate[f[r].v[r],{t,O,l}] r4=t{x, ,z} curl[{fx f fz D[fy,x]-D[fx,y]
}
Construction for the van der Waals Gas \n ll ]
Join[sol[[l]],{Rule[p,pc]}]
eq3 = p[vl]==p[v3] eq4 = p[vl]*(v3-vl)==Integrate[p[v],{v,vl,v3}] On[Integrate::gener]
.34,5.},
vmin = v I. FindMinimum[ p[v], {v,O.4}] [[2]]; vmax = v I. FindMinimum[-p[v], {v,1.}][[2]]; vtest = (vmin + vmax)/2
255
256
Eo Program Listings
.
,
P1ot[{pmax[v],p[v]},{v,O.34,5.}, P1otRange-){{O,5},{O,2}}, Frame -) True, FrameLabe1 -) {II V I l , II p ll} ]]]
1.9 Best Game Strategy: game.c
2.1 Quantum Oscillator: quantumo.m Print[lI\n Quantum Oscillator \n ll ] ["_,k_]:= S rt[("+k+l)]/2 Ii Abs[O-k]==l q[j_,k_]:= Ii Abs[j-k]!= 1 q[n_]:= Tab1e[q[j,k], {j,O,n-l}, {k,O,n-l}] hO[n_]:= Diagona1Matrix[Tab1e[i+1/2,{i,O,n-l}]]
°
Frame -) True, FrameTicks -) {Automatic, Tab1e[{O.5*j.If[EvenQ[j],ToString[j/2],III1]},{j,19}]}, FrameLabe1 -) {"lambda",lI ener yll}, P1otLabe1 -)IIEigenva1ues of h[4]11 ] evnum[n_,la_]:= Sort [Eigenvalues [N[h[n]/. 1ambda-)la]]]
P10tRange -) All, FrameLabe1 -) {"l/n",IIEO(n)"}, P1otSty1e -) PointSize[O.02], Disp1ayFunction -) dentity gr2 = Graphics[{Thickness[O.OOl], Line[{{1/20,O.559146327}, {1/7 ,O.559146327}}]}]i
.
" , , ,-
ev2[k_]:=Tab1e[{ev1ist[[i,1]],ev1ist[[i,2,k]]}, {i,Length[ev1ist]}] p1ot3:= ( Tab1e[gr[k]=ListP1ot[ev2[k],P1otJoined ->True, 1SP ay unct10n -) ent1ty, Frame -) True, FrameLabe1 -) {1I1ambda","energyll}. FrameTicks -) {Automatic,
*" Disp1ayFunction -) $Disp1ayFunction] )
E. Program Listings
Print["\n Electric Circuits \n"] eql={vr+vo==l,ir==ic+il,vr==ir r, vo==ic/(I omega c),vo==I omega IiI} numvalue = {c -> N[10 (-6)], I -> N[10 (-3)]} vosnum = vos I. numvalue flist=Table[vosnum l.r->100.0*3 s, {s,O,3}] p 0 0 va ua e s 1S , omega, PlotRange-> 0,1 , Frame -> True, FrameLabel -> {"omega","Abs[vo]"}, FrameTicks -> {{20000,30000,40000},Automatic} ] A
A
A
FrameLabel -> {"omega","Phase(vo)"}, FrameTicks -> {{20000,30000,40000},Automatic} ] vsaw - + omegares= Sqrt 1 c . numvalue N alist=Table[N[vsaw[(n-l)/256 T]],{n,256}] blist=InverseFourier[alist] plot3[fac_,w_]:=Block[{volist,vtrans,omegai,plotlist},
.
*
Table[vosnum/.{omega->omegai*(s-l),r->w}, {s,128}],{0.0}, Table[vosnum/.{omega->omegai*(s-128),r->w},
PlotRange -> All]] eq2={ir(r + 1/(1 omega c) + Iomega 1) + vo ==1, so
PlotRange->AII,Frame -> True, PlotStyle->{Thickness[0.006],Dashing[{.01,.008}], Thickness [0.003]},
, omega , plot5:=Plot [(power/.numvalue)/.r->10.0,{omega, 10000,700OO},
257
E. Program Listings
258
D1 ..... +D~-- ..... _~A11
.-
.~
-
-'::1._ _.. . .r.r ....
~
i t\t\t\t\ '
-,-
T,..na
-
•
Automatic}, FrameLabel ->{lIomega","P/PO"}]
-
~.'l
_. .
•
n!:UT1l
. .. .
-... V.au.a
•
'
... l-
•III
Print["\n Oscillator Chain \n II] , -f , 0 , -f*Exp [-I q] }, matl = { { 2f }, , 2f , -f , 0 { -f .( }. . -f . 2f -f 0 } } { -f*Exp[I q] , 0 , -f , 2f massmat=DiagonalMatrix[{ml,ml,ml,m2}] mat2=Inverse[massmat].matl ... r r - , -J.a.U.&.CL"\.,A" .... ",nopLr..l.geDv L mat2/.{f -> 1., ml -> 0.4, m2 -> 1.0, q-> x}]]}, {x,-Pi,Pi,Pi/50}] »lotlist=N[Flatten[Table[ Ma»[{# [[1]] ,Sart [#[ [2,k]]] }It, eivenlistl.{k.4}] 1]] plotl := ListPlot[plotlist,FrameLabel -> {"q",lIomega"}, Frame -> True,Axes -> None, FrameTicks ->{{{-Pi,"-Pi"},{-Pi/2,"-Pi/2"}, P
P ••
r,..
l.V,
",.."" rn."'" lin.' , ... "" rn.' lin..: ",,- "v J , V . , ... , . . . ,... J , \''' . , . . . J J ,
." - ..-oJ
,
'\
eigensys := Thread [Chop [Eigensystem [mat2 I. {f -> 1., ml -> 0.4, m2 -> 1.0, q->O.O}]]]
2.4 Hofstadter Hutterl1y: holstadt.c
1***** Hofstadter Butterfly *****1 :ft; ... ,.lnl'1 ... *~
__, .. ...1_
~.
_'L
-...
h,> ',;,.."
'h~
&
#define QMAX 400 #define SHIFT 1 mainU {
int gcd( int , int); int ie, n, nold, m, p, q, x; 1'1,.... },.1 ... .&&U
_..1_':
0 ......
...
"l.;o·nUl -
.:_ ...
-
-
char str [tOO] ;
n;
.-
nl::.;n1t'1
a '
...
-
.-
~
.
nl::.; &
.nl::.; ... av·
initgraph(ltgdriver,ltgmode,"\\tc")i settextstyJ.eU,U,l.);se'tcoJ.orlIU:;U); outtextxy{SHIFT+l00 ,::>HJ.l'--1'+QMAX+l0, "Hors'tad'ter tiu't'terrJ.y') i settextstyle(O,O,l)jsetcolor(WHITE); outtextxy(SHIFT+l00,SHIFT+QMAX+60,"Commands: eXit,arbitrary");
E. Program Listings r-
-
259
---, .... ,. I
of
\.
/* the eigenvalues for q=2 are known and have to be dravn separately */ setvievport(SHIFT.SHIFT.SHIFT+QMAX.SHIFT+QMAX.1); putpixel(0.5*QMAX.(0.5+sqrt(2.)/4.)*QMAX.WHITE); putpixel(0.5*QMAX.(0.5-sqrt(2.)/4.)*QMAX.WHITE); for(q = 4; q < QMAX ; q+=2) .[
,
.
.. y ...... 40- v ;,e,-v
I.
II
... , .. v ....
..
-'/...111
"'1 to.....
.
...''''1'' .. , .. .\
........ . ,.
,.
,.,.
.,
..,nAA -..Lv.,;,u.l.r.a..,;,u.l.r.a. -",l·lAA--..L..LV.';'U.l.r.a. -IoV • ..L/,
'-\';'U.l.r.a.·
clearvievport(); outtextxy(1.10.str); setvievport(SHIFT.SHIFT,SHIFT+QMAX,SHIFT+QMAX,1); for(p = l', P < q; p+=2) {
if ( gcd(p,q»1) continue; _.:_~
_
...
(" n .....: .... \/_. ,- _. r - .r ' , , .
, ... - "v , ,. ,.
..... , .....
....v ...... ~
..LV..L\.I.e
-
v •
.I.e
"'
,
~
........
.I.e
-,,
{
e = 8.0*ie/QMAX - 4.0 - 4.0/QMAX ; n = 0; psiold = 1.0; psi = 2.0*cos(sigma) - e; if( psiold*psi < 0.0 ) n++ ; for( m = 2; m < q/2; m++ ) .( ...
~ . . . . . . . . y~
C.~I
-
'l
(
.
...
,
"
~
(~
..
,,~
...
.\ .,
....
\
, psiold = psi; psi = psinev; ...... ,
.
r
v.v,
-
.... .. r
~
_
.
... ~ ..
,.1~
•
•
40-
}
psiold = 1.0; psi = 2.0 - e; if( psiold*psi < 0.0 ) n++ ; psinev = ( 2.0*cos(sigma) - e )*psi - 2.0*psiold; if( psi*psinev < 0.0) n++; nc.; ... l...J = nc.;· nco; = nc.;nAU· . c c . ~
I
.Lv... ,
_ au
.
n ~,
au
,
'if'n
~,
au
,"
{
psinev = ( 2.0*cos(sigma*m) - e )*psi - psiold; if( psi*psinev < 0.0) n++; psiold = psi; psi = psinev; }
psinev = ( 2.0*cos(sigma*q/2) - e )*psi - 2.0*psiold; if( psi*psinev < 0.0) n++; y,..
....
'~f~ ...... '40-
'"
nVAY
(.,:1,. ... +\,. •
I
..... ,...1\ 4O-V_ ..... ,
nold = n;
0;
.... 0;
., -:.' , ... , ... v,
,
260
E. Program Listings
.,
1..
,I ...
"1_._ -- ---r ': __
1
/* p-loop */ if (kbhitO) {str[O]=getch();getch();if(str[O]=='e') break;} l' 1* q-J.oop *1 closegraph(); } /* main */ };
;..,1- lI'''.-I (
.r.
;..,1-
Jll
;..,1- h'\
Q
if( b==O) return a; return gcd(b,a%b); }
2.5 Hubbard Model: hubbard.m Print ['I\n Hubbard model \n"] s1tes=lnputL" Number of s1tes: "J ; Pr1ntL""J particles=Input["Number of particles: "]; Print [1111] spinup=Input[IIHov many of them are spin-up particles? II]; Print [1111] spindovn=particles - spinup tkin=-2.*t*(Sum[N[Cos[2*Pi/sites k]], -1'\ /.,1 ~, nn.... r, llr -~'nn.... r( . . I'll '\1 ~ C'••
_rvr,,__ ... r".D~
.- ... -.1_'::' __
...... ,
1.11'
{k,-Floor[(spindovn-1)/2],Floor[spindovn/2]}]) Print [II II] Print[1l The ground state energy for U = 0 is: II , tkin] .le:It = t'ermutat1onsl TaD.lel l.:IL J None, Frame -> True, FrameLabel->
261
E. Program Listings
262
'[IITT/t- 1I
.
lIinn'h1 ...
...... v
, ..... 11
...
"
1"1~1
)
plot3:= (groundstate = Map[{#[[1]],#[[2]]/sites}i,state]; g1 = ListPlot[groundstate,Frame->True,Axes->None, PlotStyle->PointSize[O],PlotJoined->True, l'"rameLabe.l->1."u/t ,"linergy per s1te/t"}, DisplayFunction -> Identity J; f [u_ ,0] = 1/4 ; f [u_ ,0. 0] = 0.25 , fru x 1 = BesselJ ro xl *BesselJ rt xl/(x*l1+Exnrx u/21))' .nlnt:l;~t: = TJOlhlAr.fn -40*
.
..
r~r ......1
~
~.
u
~.
,
"~
.,
f .... n
,~.
s::: s:::')1.11. f •• n "I
~
1
.~.
,
• , ~ ,. ')1.1 -" .. ,
g2 = ListPlot[plotlist, PlotJoined -> True,DisplayFunction -> Identity, PlotStyle -> Dashing[{0.01,0.01}]]; OlnowLgl, g", U1Sp.1ayruncl;1on -7 i)U1Sp.1ayruncl;10nJ }
-
3.1 Population Dynamics: logmap.c
1***** Population dynamics *****1 #include #include #include ..... v
........................" ,
main() {
void channel{double); int gdriver=DETECT,gmode; char ch,str[100]; double xit=0.4,rmin=.88,r; int x,y=50,i.ir; ..: ...: ............
....
... II'" . , 11\ \ 'V_ ... '-0-- .... --, ....maxx=getmaxx(); maxy=getmaxy(); setcolor(RED); settextstyle{1.0,1); outtextxy(100,maxy-80,1I Lop:istic map x=4*r*x*(1-x)II); settextstyle(O,O,1);setcolor(WHITE); outtextxy(50.maxy-30, II Commands: lower,higher,refresh,print r,channel,arb.,exit II) ;
• II. . ...lI_": .... _
(1
"' ..+u;
- _. _ .. 1
4.
-
,_.
. .
1 """"vv "",,"vu_1nn i ) .
;"1\, • J' '--J ---"
. /1· _ _ ..: _, ..... / / ___•• _1
while(1) {
X1t=4.*r*x1t*\1.-x1t); x=xit*maxx; putpixel(x,y,WHITE); if(kbhitO)
E. Program Listings
r _ . ...: • •1. ( - - - - -•• '0'
-'- ( \ \
{
case ' l' : case ' h' : default : case ' e' : case ' c' : case 'p' :
" ,
if (y«maxy-100» y+=1;break; if(y>1) y-=1;break; getch {) ; break; closegraph 0 ; exit(1); channel(r);break; sprintf(str,1I r= Y.lfll,r);
..
'(1 ,v str)' w
'h"''''J:lllr·
' .... , . ... ,~ ....... .,~ , -(" \ ,.'} /* switch */ r=1.-(1.-rmin)*y/(maxy-100); for(i=0;i {{O,1},{O,1}}, PlotStyle -> PointSize[O.015], .;",... _'> T,'" 1 • n;"'.....l .... ,
_':J_T ..: 0
_+n,_ _ "'+v
r, . : '1" n,"
.. _ _ _ , .
__
. .
.... , ..... v
...
...
.-
.... - -. ..- -....
_.... .r.rn 11. .r~" 1 ~ ~ , , , , , "', ,
...........
PlotStyle -> Thickness[O), DisplayFunction -> Identity ) ; g4=Graphics [Text [ StringJoin[t1r = ",ToString[r]],{O.5,O.05})]; g5=Graphics[Line[{{O,O},{1,1}}]); Shov[g1,g2,g3,g4,g5,PlotRange -> {{O,1},{O,1}}, AspectRatio -> Automatic,
...
n..: __,
.
-'> T....,....
...
_
.
'",-
_.... cl.>n..: ._,
.
"
_
...
.1\ ,
"
h[x_)=97/25 x(1-x) hl[n_]:=NestList[h,N[1/3),n] hl[n_,prec_]:=NestList[h,N[1/3,prec),n) tab:=TableLtprec,PrecisionLLastLhlL100,precJJJ}, {prec, 16, 10O}) plot4:=ListPlot[tab, Frame -> True, PlotStyle -> PointSize[O.01), • ",h... l -'>
-.r"D__ .. -
"~_~,,,_
._-___ ,_•• , ....... .- ......+1.
",-4' ~
II.
.:/
.,
" .............................
""
__ "
,
.I J
period[1)={c,1} accuracy=30 mUl.t=30 period[n_]:=period[n]=Join[period[n-1], correct [period [n-l))) correct[list_):=Block[{sum=O,li=list,l=Length[list)}, Dorsum+=lirHll ..fi2 .Ill· Ti'rnrltUH... .,ml H rr1l1=o . 1; rr1l1~1l· ,- .- '- .
--
1 .. 1
g[n_,mu_):=Block[{x=Sqrt[mu),l=Length[period[n))},
E. Program Listings n.... rv=C!.......+r_.. ~(_1\-( .....................Ir...l rr....... ll\ vl -.. ~.
&-~-
..... , ..., , .... ,
1' .•
'::I
_~r
~~
~~'
.. , .....
_1I'L' •
265
.
fr[n_] :=fr[n] =(find=FindRoot [g [n,mu] ==mu,{mu, {15/10, 16/10}}, AccuracyGoal->accuracy, WorkingPrecision->accuracy, Maxlterat1ons->max1tJ; mu/.find) rr [n_] : = rr [n] = (1+Sqrt[1+4*fr[n]])/4 delta[1]:= Print[" The value of n is too small"] deltar21:= Printr" The value of n is too small"l ~Al+'Sllrn 1·= ~Al+'Sllrnl=(~n,.+.r1 .. ~ ,rn-1l1-~n,.+.r1 ... 4*~,.rn ·?ll'/ (C!:'....+r1 .. ~. r...ll ~, r....111\ . , - .C!........:r.... &. &feigenbaum := Do [Print [" n = ",n, " Feigenbaum constant = ",delta[n]] ,{n,3, 1O}] ~'
~.
....
~.
~.
....
3.2 Frenkel-Kontorova Model: frenkel.c /***** Frenkel-Kontorova Model #include #include #include #include
*****/
_ ....... f\
"
..
r
int gdriver=DETECT,gmode; int xs,ys,color=WHITE,maxx,maxy; long nsum=O; double k=1.,sig=.4,p=O.5,x=O.55,pi=M_PI,xnev,pnev,h=O.,vind=O., xold,pold; char ch,str[1000]; initgraph(lgdriver,lgmode,"\\tc"); -
-
,
,f\.
O'
'\ ~"""'J6-V~"""'J'"
settextstyle(1,O,1);setcolor(RED); outtextxy(150,maxy-80,"Frenkel-Kontorova Model"); settextstyle(O,O,1);setcolor(WHITE); outtextxy(100,maxy-35, "Commands: exit, print, nev start, clear, arbitrary"); xold=x; pold=p; vhile(1) {
n..... u=n~1r/')
In;*",; ... (')
_.0__ -r.o--.._,
£
£
£
.
*n;*v\' £
xs=fmod(xnev+100000.,1.)*maxx+1; ys=(1.-fmod(pnev+100.,1.»*(maxy-100)+1; putpixel(xs,ys,color); V1n PointSize[O.013]] hxO:=Table[{x,h[x,.336]},{x,.15,.2,.001}]
PlotStyle -> PointSize[O.013]]
a
Ice: slerp.c
***** Fractal Lattice ***** #include #include main 0 {
" getch()j setcolor(WHITE)j while ( !kbhitO)
.
267
E. Program Listings
268
. .
'\
• VA 1
.
(nt: '
Y.
.nt: .v.
WH
Tto: J •
getch();getch(); closegraph(); }
3.3 Fractal Lattice: sierp.m Print[lI\n Generates and Plots a Sierpinski Gasket \n"] list={{{O.,O.},{.5,N[Sqrt[3/4]]},{1.,O.}}} mult[d_]:=Block[ {d1.d2,d3}, d1={d[ [1]] , (d[[2]]+d[[1]]) *.5, (d[ [3]] +d[[1]]) *. 5}; d2=d1+Table[(d1[[3]]-d1[[1]]),{3}]; d3=d1+Table[(d1[[2]]-d1[[1]]),{3}];
. .-
, ~
. --,--,--.1
.T..:J1
.... ,
.'.rr,·,.,.
..:Jt'J
.,
..:J":2'\.
.,.
1 J
."1
,\,.&..£.i> .. ~ ,y.&.u
,
list2=Map[mult,list]; list=Flatten[list2,1]; plotlist=Map[Polygon,list]; Show[Graphics[plotlist], ASDectRatio -> Automatic]]
3.4 Neural Network: nn.c and nnf.c ~Ul..
.
!1 . L 1
n"n.
TlA'Il..
Viol. '-I.LJ-
'"' ~i:)
/*****
.1. VUJ.'y'
Neural Network - Reading from a File
IFl.nC.LUQe ~Sl;Q.Ll.D.n,;> JJl.ncluTrue, PlotRange - > All, AspectRatio->Automatic,Frame -> True, FrameLabel -> {"q","p"}, RotateLabel -> False, PlotStyle -> Thickness[O.OO3] ] phase3:= Euler[{D[hamilton, pl, -D[hamilton, q]},
. I'... u ....... ..
f_ -
'I' • "VA __
_'\.
.."
1'''''
1"'. __ ~ V _ .... •
.n..
. ..
'r
_I'\'l..
J_l..":1'\
"1'---' 1'-'"
n..
,A
-
~ 'Y'
...
.
J11'\
...1.'l..1
.. --, --.....
.......
..
,.
. . . . U&II...
"' 60_
.......... ,
,
....... , ......... ,
FrameLabel -> {"q","p"}, RotateLabel -> False, PlotRange -> {{-2.3,2.3},{-1.85,1.85}}]
.....
4.2 Chaotic Pendulum: pendulum.c /
.....
Chaotic Pendulum
/
"'i"... "1nA1: ttnllhl ... 'include 'include 'include *inc.Luue ....sl Th; •
r,-
_~
_ 7'"'" "
rol
.. .. .
- _.
',.
',. r_1
• .1\ ..... f.. .. 1 ... , AxesLabel -> {IIt". "X". "U"}]
_ _ 'W . . . n.'
--.,
...
__ ....
11.1.
~
1\
~
~
~"-
, _· ...oJ,
plot5:=ContourPlot[-u2[x.t].{t.-l.l}.{x.-10.10}. PlotPoints->100. ContourShading->False. PlotRange -> All. ContourSmoothing -> 4. -
9
..
.
_'> J'"+" " v ll'\.
h ...l
....
........_,
1"1
...
_ .....
1:".. ' - -
rn ..
......
~,
n
....
1"
..
.
n ~ LO" ... ·.... n-· ......A ·....... ·"'oJ .. I'
....
v.~·~
I'
plot6[tt_:0.3]:= (uprime[x_]=D[u2[x.tt].x]; x=-10.0; exactlist={{x.u2[x.tt]}}; d=0.07; upl=uprime[x]-2; Wh11eLx -
,
::: " "7A
ro OO?l
Av ...... _ ..... v,..._ ... 1 .~
,
275
276
E. Program Listings ...l
A ~ T.'I'YIlo_...l
co
,'I_
~
•• --11-
&'
.
.
i·
10
Available on CD-ROM only. D.~
nanaom
l~umDers:
ranaom.m
Print ["\n Random Numbers \n ll ] xO = 1234 a = 106 c = 1283 m = ~n7f\ rndm[x_] = Mod[a*x + c,m] uniform = NestList[rndm,xO,m+1]/N[mJ triplet = Table[Take[uniform,{n,n+2}],{n,1,m,3}] . .., . il;J UIl~"v'C ... "v.l.~ napL\tt/O)q.l.'l;Ltt.ttJJf£, . Pl.o't 1: =;:mow Lurapn1CS~lJ Lu'o1n'ti)1Ze LV. VVIiJ , Map[Point,unitvectors]}], ViewPoint -) {2,3,2}]
'-
........
.
= .f276. 164. 442.l/m (* vector closest to .f0 0 Ol *) hi h? h~ Rn~n . llnH~ rAll *) {-113. , 172., 7.}/m = = {173., 113., -172.}/m = {345., 120., 570.}/m ,. ... , ... vp - W"'\:1"'DJ. ___ , l.V,v,J.vvr Pl.o't:l := i)nowLurapn1CS;JlJL1.1"01n'ti)1ZeLv.vV4J, Map[Point,triplet]}], ViewPoint -) vp] vO (* b1 b2 b3
uni = Table rRandomrl ..fm+211 . t::ri = T~hlArT~lcArllni .(nn+2l1 .(nmll univec = Map[(#/Sqrt[#.#])&,tri] plot3:=Show[Graphics3D[{PointSize[0.004], Map[Point,univec]}], ... . ,- _.... , .......................- .... l.~,~,~rJ
5.1 Random Numbers: mzran.c
1***** Random Numbers *****1 #define N 1000000 unsigned long x=521288629, y=362436069, z=16163801, . ,.=1 n=11':l11 unsigned long mzran() { unsigned long Sj ts=y ~x+C)j c=Uj)" {s=y-(x+c)-18j c=1j} else x=yj y=Zj Z=Sj n=69069*n+1013904243j return (z+n); 1t~y)X+C)
E. Program Listings l
maine) {
double r=O.; .long l.; printf("\n\n 1,000,000 random numbers are generated II , II and averaged.\n\n"); for (i=O;irkill) 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 rrv··1+1m3y/?1>O)
,; , .
... 1",...
J
.
, 3' .
"
'
l.
5.3 Percolation: perc.c and percgr.c percgr . c is aVaiIaOle on
I.....
~
Percolation •••••
'include 'include 'include 'include
.
~
\jU- tU
amy.
J IVI
1
..... ;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;i1:;. 1 ')')
T
.... , nteractlOn - attractive 183 - magnetic 172 InteractIOn potential !J;j Interference pattern 146,153 Interpolation 141 Inverse 61,221
Function - Boolean 108 - nonlinear 93
~
~'l
n
T
1nn ... .,.,
u
~~
T
1 '>0
T.'I
&:.').,
Initial condition 61,83,121,165 Initial state see state, initial Initial value 116,132 Imtlal-value problem 104 Initialization 138 int 5,225 Integrate 9,11,37,220
- inverse 13,55 Fractal 102,105,123,173 ttrequency - angular 52 - fundamental 146 - incommensurate 97 ,"
110 11'>
1
I
fH ... ,..1 111'1 ...
R hLl
(;101'10(;1
T.'I
_.n
,
;.
oJ
for 5,33,179,196,226,229 Force - gravitational 120 - perIodic l~~ Forward-two-point formula 137 Four-cycle 83,90 Fourier 8, 15
""-
149
110')
'r--
48,51,71,73,75,119,
Hamiltonian
•
24
,
'>0 1~'l
~
~
T
.1
T
".
'lIer •
•
15" 21 1
u",l11 0 •
Ising ferromagnet
~I:;.
1?~
192,197
285
286
Index
Isotropy 165 Iteration 84 - inverse 85,90,150
KAM orbit 98 100 Kernel 20 Keyboard buffer 206 Kirchhoff's law 52 Koch curve 106
Lattice - cubic 164 - gas - square 172 - triangular 172 - vector, primitive 159 - vibration 59, 62 - rule
Minimax theorem 44 Minimum, absolute 202 Mod 96,158 o e unc ion o u e Modulo function 95, 158, 161, 187, 227 Molecular dynamics 118 Momentum 0 erator 64 Monomer 102 204 Monte Carlo step 210 Multiparticle state 71, 74, 190
107
Leath, P.L. 177 Length 4,76,216 Line Line integral 36 LinearProgramming 42,45 Liouville's theorem 94 Liquid 39
83,91
Network - electrical 52 - linear 54
Nonlinearity 7 NonlinearRegress Normal mode 60
25,217
, 132 185,191
Index
- algebra 74 - unitary 149 Optimization - com inatorial 203 - continuous 201 - discrete 201 - linear 42,44,201
287
190, 198 Phase velocity 152 Phonon 59,62 Pixel 86,103,134 Plot 8, 141, 213 Plot3D 32,213 PlotRange 8
,
,
- superstable 84,85,90 Order - magnetic 172 r er parameter Oscillation 138 - damped 126 - longitudinal 59
Oscillatory circuit
Poincare section 82,94, 123, 126 Point 159 Pointer 5, 230, 233 Polygon 10 Polymer configuration 183 Polymer dynamics 183 Polymer molecule 102,182,186
52
54,58 27 23,28 37,214
42,43,46 19,210
,
Power spectrum 19 Precision 91 Predictor-corrector method
119
printf , Probability 43, 145 - density 164
9
122
172,175
74,216 49,83
Phase space
9, 11, 120, 122
Quantum Monte Carlo method
78
288
Index
5,103,158,168,177,206,230 RAND~AX 5,168,170,230 Random 4,158,159,214 random 96 Random motion 164 Random number 4,21,46,113,157, 205
y , , - time-dependent 144 Schroeder, M. 106 Sech 138 Self-avoidin walk SAW Self-intersection 184 Self-similarity 104 Sequence, periodic 158
- - subtract-with-borrow 160 - normally distributed 29 - uniformly distributed 162, 195 Random vector 102 Random walk 102, 103, 164, 182, 183, 189 Rectangular voltage 58
Series representation 145 Shooting method 132,135 Show 31,213,216 ShowPro ress 26 Sierpinski gasket 104 Sign change 67,68 Simplify 38,220
Relaxation time 195 Renormalization group theory 193 Re lacePart 75 Reptation 184-186 Resonance 54,56,57 - curve 56
Single-particle state 71 Site percolation 176 Size, average 165, 173 Soliton 136 Solution - analytic 41 - numerical 41,47,51, 71,115, 141
rand
174,
, Richardson extrapolation Rosenblatt, F. 109 Rosenblatt rule 110 RotateLeft 21,138,141 RotateRight 141 Round 119 Round trip 200
163
118
Spectrum 63 Spin configuration 191 Spin correlation 80 Spin lass 202 Sqrt 9,49,212 Stability 143 - condition 143
State 94 - commensurate 95,97 - incommensurate 98, 99 - initial 83, 150 - quasiperiodic 98 - stable 93 - stationary 47, 145, 191
182
Index
, - stochastic 44 Stroboscopic illumination 123 struct 103,178,186,205 Sturm se uence 67 Subharmonic 83 Sum 32,75 Supercomputer 191
Two-cycle 83 Two-person zero-sum game 43, 46 Two-phase line 39,40 Two- hase mixture 40 Two-soliton solution 142 Type declaration 5, 103, 225 typedef 161,186,205
,
, switch 112,169,228 Symmetry 66,68,69,74,78,131,133, 145,146,193 - reaking, spontaneous 19 Synapse 106 Synaptic plasticity 108 Synaptic strength 108
Taylor expansion Temperature - critical 39, 41 - norm lze Tensor 4,30 TeXForm 12,77 Thickness 31
unsigned long int
, 161
Vacuum 72 van er s equatIon van der Waals gas 38 Variance 24,162,200 Vector 4,30,229
116, 132, 139, 153
Time derivative 140 Time evolution 149, 153 - operator 148 - quantum-mec amc Time scale 123,198 - characteristic 152 Time series 110
- Gaussian
Transition probability 185, 191, 194, 196,202 Translation 60 - opera or - t eorem Traveling salesman 200
Winding number 95,97,99 - rational 97 Witten, T.A. 163 or 1ng reC1S10n
155 183 107,112
,
Zaman, A.
160
289
L
~'Gdby~
CN'
~
CP
L
~
;:,~
.)0~
~nrinn~r
-'" t"'. •• • ~ ~ •
and the environment At ~pnnger we nrmly Delleve tnat an international science publisher has a special obligation to the environment, and our cornorate nolicies consistently. ~
~
reflect this conviction. We also expect our business partners """,;11 ... .1" -.1"
.1"
•U&&&&U,
.
.u, .1"
.
_1. OJ
OJ
manufacturers, etc. - to commit themselves to using materials and , , ,
.
r-
"
Ulal uu llU l
.1"
the environment. The paper in this book is made from low- or no-chlorine pulp and IS aCId tree, In contormance , , r . , . . "
WIUI
IIII~J
I'"
I, Jill ....
~I
permanency.
~
-~
•
~4~ ~
Springer
.U"
IUI.1"
T
w. Kinzel/G. Reents
Ph~sics bq C0m PUte r
Computational Physics has undergone rapid development in recent years and is being integrated into physics education as a standard part. This course, intended for upper-division undergraduate or graduate students, was designed by W. Kinzel and G. Reents as a textbook in computational physics but may also serve as a supplement to courses in theoretical physics.
It is an introduction to the solution of physical models by computer. The programs developed in this book are based on the modern computer languages Mathematica® and C and are written for PCs as well as for workstations. 28 examples from different fields of physics are worked out, including chaos, fractals, the Hofstadter butterfly, phase transitions, MonteCarlo simulations, percolation, polymers, combinatorial optimization, neural networks, and game theory. Detailed explanation of the algorithms and computer programs together with source files and graphics routines help the student gain thorough experience right from the start. System requirements: Mathematica® 2.2 or 3.0, C compiler.
ISBN 3-540-62743-X
I I II
9 783540 627432
http://www.springer.de