computational physics 2 - reading · fortran 95/2003 explained by michael metcalf and john reid...

38
Computational Physics 2 Module PH3808 10 Credits by Dennis Dunn Version date: Tuesday, 13 January 2009 09:26 Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics Computational Physics– Computational Physics

Upload: others

Post on 01-Sep-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

Computational Physics 2

Module PH3808

10 Credits

by Dennis Dunn

Version date: Tuesday, 13 January 2009 09:26ComputationalPhysics–C

omputationalPhysics

ComputationalPhysics–Com

putationalPhysics

ComputationalPhysic

s–

ComputationalPhysics

Com

puta

tiona

lPhy

sics–

ComputationalPhysics

Com

puta

tiona

lPhy

sics

ComputationalPhysics

Com

puta

tiona

l Phy

sics

ComputationalPhysics

Com

puta

tiona

l Phy

sics–

ComputationalPhysics

Computational Physic

s–

Compu

tation

alPhy

sics

Computational Physics– Com

puta

tiona

lPhy

sics

Computational Physics– Com

puta

tiona

lPhy

sics

Computational Physics– Com

puta

tiona

l Phy

sics

Computational Physics–

Compu

tation

alPhy

sics

Computational Physics–

Computational Physics

Com

putational Physics–

Computational Physics

Com

putationalPhysics–

Computational Physics

ComputationalPhysics–

Computational Physics

ComputationalPhysics–

Computational Physics

ComputationalPhysics–Com

putational Physics

Page 2: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

2

Copyright c©2003 Dennis Dunn.

Page 3: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

Contents

1 CHAOS 11

1.1 Objectives 11

1.2 Further Reading 11

1.3 Background 11

1.4 A Non-Linear Oscillator 11

1.5 Linear & Non-Linear Systems 12

1.6 Phase Space Portraits 13

1.7 Sensitivity to small perturbations 13

1.8 Exercises 14

2 ASPECTS OF OBJECT-ORIENTED PROGRAMMING 17

2.1 Objectives 17

2.2 Object-Oriented Programming 17

2.3 EXERCISES 20

3 QUANTUM STATISTICS: Application of Numerical Integration 23

3.1 Objectives 23

3.2 The program 23

3.3 The Fermi gas 24

3.4 Bose-Einstein condensation 27

3.5 EXERCISES 29

4 THE RANDOM WALK 31

4.1 OBJECTIVES 31

4.2 THE RANDOM WALKER 31

4.3 The Random Walker on the Computer 32

4.4 THE RANDOM WALKER AND PERCOLATION 32

4.5 THE SELF-AVOIDING WALK (polymers or spaghetti) 33

Page 4: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

4

Index 36

Page 5: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

INTRODUCTION TO THE MODULE

Version date: Thursday, 30 August, 2007 at 11:54

Introduction

In this module you will be taught techniques employed in computational science and, inparticular, computational physics using the FORTRAN95 language. The unit consistsof four ‘computer experiments’, each of which must be completed within a specifiedtime. Each ‘computer experiment’ is described in a separate chapter of this manual andcontains a series of exercises for you to complete. You should work alone and shouldkeep a detailed record of the work in a logbook that must be submitted for assessment atthe end of each experiment.

For three of the four projects, there will be a supervised laboratory session each weekand further unsupervised sessions.

There will be no supervised sessions for the fourth project: This will be an exercise inindependent learning.

The Salford Fortran95 compiler will be used in this course, and this may be startedby double-clicking on the Plato icon under the “Programming - Salford Fortran 95”program group. A “FTN95 Help” facility is supplied with this software and can befound within the same program group. This help facility includes details of the stan-dard FORTRAN95 commands as well as the compiler-specific graphics features. All ofthe programs needed during this course may be downloaded from the Part 2 - PH2401Programming Skills page on the department’s web-server:

(www.rdg.ac.uk/physicsnet).

Web Site Information

In addition to all the chapters and programs required for this course, there are links toother useful sites including a description of programming style; a description of com-putational science in general and FORTRAN programming in particular; a tutorial forFORTRAN90; and a description of object-oriented programming.

5

Page 6: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

6

References

Programming in Fortran 90/95

By J S Morgan and J L Schonfelder

Published by N.A. Software 2002. 316 pages.

This can be ordered online from

www.fortran.com $15

Fortran 95 Handbook

By Jeanne Adams, Walt Brainerd, Jeanne Martin, Brian Smith, and Jerry Wagener

Published by MIT Press, 1997. 710 pages.

$55.00

Fortran 95/2003 Explained

By Michael Metcalf and John Reid

Oxford University Press ISBN 0-19-8526293-8

$35.00

Fortran 90 for Scientists and Engineers

By Brian Hahn

Published by Arnold £19.99

Fortran 90/95 for Scientists and Engineers

By Stephen J. Chapman

McGraw-Hill, 1998 ISBN 0-07-011938-4

$68.00

Numerical Recipes in Fortran90

By William Press, Saul Teukolsky, William Vetterling, and Brian FlanneryPublished by Cambridge University Press, 1996. 550 pages. $49.00

A more complete list of reference texts is held at

http://www.fortran.com/fortran/Books/books.html

where books can be ordered directly.

Logbooks

You must keep an accurate and complete record of the work in a logbook. The logbookis what is assessed. In the logbook you should answer all the questions asked in the text,

Page 7: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

7

include copies of the programs with explanations of how they work, and record detailsof the program inputs and of the output created by the programs. On completion of eachchapter you should write a brief summary of what has been achieved in the project.

I am often asked what should go in the logbook. It is difficult to give a precise answer tothis since each computer experiment is different but as a guide: it should have

• a complete record of your computer experiment;• sufficient detail for someone else to understand what you were doing and why; and• for someone else to be able to repeat the computer experiment.

In particular should also include:

• program listings;• a description of any changes you made to the programs;

If you have made a succession of changes, you should not reproduce the completeprogram each but simply specify what changes you have made and why you havemade them.

• the data entered and results obtained from your programs (or, if there are a verylarge number of results, a summary of these results);

• a comment on each set of results;You will lose marks if you simply record masses of computer output without com-menting on its significance.

• descriptions of any new techniques you have learned.

It worked!

A statement in your logbook of the form ”I tried the program and it worked” will notbe looked on favorably.

• What inputs did you provide to the program?• What output did you obtain?• What evidence do you have that this output is correct?

Program Testing

It is always safe to assume that a program you have written is wrong in some way. Ifyou have made some error with the programming language then the compiler will tellyou about this: it may not always tell you precisely what is wrong!

However it may be the case that what you have told the computer to do is not reallywhat you intended. Computers have no intelligence: You need to be very precise in yourinstructions.

Every program should be tested. You do this by giving the program input data such thatyou know, or can can easily calculate, the result. If possible your method of calculation

Page 8: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

8

should be via a different method than that which the computer is using: the method youhave told the computer to use may be incorrect.

Only when the program has passed your tests should you start to use it to give you newresults.

Module Assessment

The module comprises 4 computational projects. A record of each project must be keptin a logbook and the logbook submitted for assessment by the specified deadline. Thefinal assessment will based on the best 3 project marks.

Each project will be marked out of 20. A detailed marking scheme is given, in thismanual, for each project.

Guidelines on the assessment are given below.

Late Submissions

If a project is submitted up to one calendar week after the original deadline 2 marks willbe deducted.

I am prepared to mark any project, which is more than one week late, providing it issubmitted by the last day of Spring Term. However for such a project 4 marks will bededucted.

Extensions & Extenuating Circumstances

If you have a valid reason for not being able to complete a project by the specifieddeadline then you should

• inform the lecturer as soon as possible; and• complete an Extension of Deadlines Form. The form can be obtained from the

School Office (Physics 210).

If you believe that there has been some non-academic problem that you encounteredduring the module (medical or family problems for example) you should complete anExtenuating Circumstances Form, again obtainable from the School Office, so that theDirector of Teaching & Learning and the Examiners can consider this.

Feedback

In addition to comments written in your logbook by the assessor during marking, feed-back on the projects will be provided by a class discussion and, when appropriate, by

Page 9: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

9

individual discussion with the lecturer.

There will be no feedback, apart from the mark, on late submissions.

Assessment Guidelines

This module is assessed solely by continuous assessment. Each project (which corre-sponds to one chapter of the manual) is assessed as follows.

The depth of understanding and level of achievement will be assessed taking into accountthe following three categories:

1. Completion of the project (0 – 17 marks)Completeness of the recordDescription and justification of all actionsFollowing the documented instructions, answeringquestions and performing derivations etc.

2. Summary (0 – 3 marks)• Review of objectives• Summary of achievements• Retrospective comments on the effectiveness ofthe exercises

3. Bonus for extra work (0 - 2 marks)• Any exceptional computational work beyond therequirements stated• An exceptional depth of analysis• An outstanding physical insight

I should point out that bonus marks are only rarely awarded and, in any case, the totalmark of a project cannot exceed 20. Unfinished work will be marked pro rata, unlessthere are extenuated circumstances.

If you are unable to attend the laboratory session you should inform the lecturer Dr DDunn by telephone 0118 378 8538 or by email [email protected]

Plagiarism

In any learning process you should make use of whatever resources are available. Inthis course, I hope, the lecturer and postgraduate assistant should be valuable resources.Your fellow students may also be useful resources and I encourage you to discuss theprojects with them.

However at the end of these discussions you should then write your own program (orprogram modification). It is completely unacceptable to copy someone else’s program

Page 10: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

10

(or results). This is a form of cheating and will be dealt with as such.

I should point out that such copying (even if slightly disguised) is very easy to detect.

Time Management

There is ample time for you to complete each of these projects providing you manageyour time sensibly.

You should aim to spend at least six hours per week on each project: that is a total ofabout 18 hours per project.

Each project is divided into a number of ’exercises’ and each of these exercises is allo-cated a mark. This mark is approximately proportional to the time that I expect you tospend on the exercise. You should therefore be able to allocate your time accordingly:It is not sensible to spend half of the available time on an exercise which is worth only aquarter of the total marks.

Each of the projects below is given a deadline. You should not take this as a target. Youshould set yourself a target well before the deadline.

Projects

• Chaos [Deadline: noon, Wednesday – Week 3 Spring Term]• Object-oriented programming [Deadline: noon, Wednesday – Week 6 Spring Term]• Quantum Statistics [Deadline: noon, Wednesday – Week 9 Spring Term ]• The Random Walk [Deadline: noon, Wednesday – Week 2 Summer Term]

The ’Random Walk’ project will be unsupervised and is an exercise in independentlearning. Nevertheless the lecturer will be available for consultation.

Page 11: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

Chapter 1

CHAOS

Version date: Tuesday, 7 March 2006 at 09:33

1.1 Objectives

On completion of this chapter students will have investigated the behaviour of a simplesystem that displays deterministic chaos. They will also have encountered and appliedsome common graphical and analytical tools for nonlinear systems.

1.2 Further Reading

“Fractals and Chaos - An Illustrated Course” by Paul S. Addison (IOP 1997).

1.3 Background

You have encountered the topic of chaos in your Part I module ‘Concepts in Physics’and so should be familiar with the basic idea that chaotic systems are characterised bytheir extreme sensitivity to initial conditions. This means that whilst chaotic systemsare deterministic, they are also unpredictable because in the real world one can neverknow precisely the starting conditions. Even computers have limited accuracy, with realnumbers being typically stored to 8 or 15 significant figures.

In this chapter you will use the same numerical techniques learnt earlier in one of thecomputational modules (specifically ’Equations of Motion in Physics’) to investigate asimple nonlinear dynamical system that displays chaos and other exotic features. Youwill also be asked to display your data in appropriate ways to highlight certain featuresof the results.

In this project there will be little actual program writing. You will be using existingpackages as part of a computer experiment to map out the properties of a particularnon-linear system.

11

Page 12: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

1.4 A Non-Linear Oscillator 12

1.4 A Non-Linear Oscillator

The Duffing oscillator is very similar to the forced, damped harmonic oscillator, usedas an example in ’Equations of Motion in Physics’, except the harmonic spring with arestoring force proportional to displacement is replaced by a nonlinear spring where therestoring force is proportional to the cube of the displacement. Its equation of motionreads

md2x

d t2= F0 cos (ω t)− rd x

d t− s x3, (1.1)

where, as usual, x(t) is the displacement of the oscillator from its equilibrium position attime t, m is the mass of the oscillator, s is the ‘spring stiffness’, and F0 is the amplitudeand ω the angular frequency of the driving force.

The frictional damping force is proportional to the velocity of the oscillator and r is theconstant of proportionality. For simplicity we may set

m = s = 1,

so that r, F0 and ω are the only parameters.

Once the control parameters (r, F0 and ω) have been selected, this equation of motioncan be solved for any initial displacement and velocity (x0v0) using the same techniquesemployed in ’Equations of motion in physics’. It has been found that this oscillatordisplays a variety of exotic behaviours, including multiple periodicity and chaotic tra-jectories.

1.5 Linear & Non-Linear Systems

A system is some physical system with an input i (t) and an output o (t). In the systemdescribed by the above differential equation the input is the force F0cos (ωt) and theoutput is the diplacement x (t).

1.5.1 Linearity

In a linear system if the input i (t) is sinusoidal then, after any initial transients havedecayed, the output o (t) is also sinusoidal with exactly the same frequency.

This means that the output (and the input) will have only one Fourier Component (at thefrequency of the input).

Page 13: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

1.6 Phase Space Portraits 13

1.5.2 ’Simple’ Non-Linearity

In a non-linear system but where the non-linearity is, in some sense, small then if theinput i (t) is sinusoidal then, after any initial transients have decayed, the output o (t) isperiodic with exactly the same frequency. However it will not be simply sinusoidal.

This means that the output will have Fourier Components at frequencies which are mul-tiples of the input frequency.

1.5.3 ’Exotic’ Non-Linearity

In a non-linear system but where the non-linearity is, in some sense, large then, in addi-tion to the ’simple’ non-linearity described above, more exotic behaviour can occur.

It may happen that the output has Fourier Components at frequencies which are simplefractions of the input frequencies – so-called sub-harmonics. For example 1/2, 1/3, 1/4.If the fraction is 1/n then this means that the output is periodic but with a period whichis n times the input period.

For n = 2 this is described as period doubling.

Period doubling, period tripling, etc are usually precursors to chaos.

1.5.4 Non-Linearity & Chaos

In a non-linear system which exhibits chaos the output, corresponding to a sinusoidalinput, is not periodic. The Fourier Components of the output then exist for a continuumof frequencies and not just at discrete frequencies.

1.6 Phase Space Portraits

A convenient way to visualise the behaviour of the oscillator is to chart its trajectory inphase-space, that is to plot its velocity v(t) against its displacement x(t) for all time.

If this oscillator behaves like a linear system (as it does for small values of F0/m) then,after the initial transients have died out:

x (t) = A cos (ωt− φ) , v (t) = −Aω sin (ωt− φ)

The phase space trajectory thus converges to an ellipse since

x2 + v2/ω2 = A2.

The ’converges to’ rather than ’is’ is needed because the initial transient motion is notin this form.

Page 14: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

1.7 Sensitivity to small perturbations 14

This ellipse in phase space is said to be an attractor for the trajectories. This meansthat wherever the initial point in phase space the motion will eventually follow a simpleelliptical orbit.

More complicated oscillations of the oscillator will produce more complicated phasemotion. Nevertheless, if after the initial transients, the oscillations are periodic the phasespace attractors will be closed orbits.

The higher the periodicity, the more loops the closed attractor will have. However notall initial conditions will necessarily lead to the same attractor, even if the control pa-rameters (r, F0) remain unchanged. Thus different attractors have different basins ofattraction, which are the regions of phase space from which trajectories starting at timet=0 will be drawn to the attractor.

The phase space orbits for chaotic systems are different in nature. They are not closedorbits since the oscillations are not periodic.

Furthermore since chaotic systems have extreme sensitivity to initial conditions, nearbytrajectories in phase space must diverge in at least one direction. Chaotic systems aresaid to have strange attractors.

1.7 Sensitivity to small perturbations

A characteristic of chaotic system is the extreme sensitivity to small perturbations. Thisshows up particularly in the phase motion.

We will investigate this computationally by first solving for the displacement x(t) andthe velocity v(t) over a long time – several hundred input periods. Then we repeatthe calculation exactly except that at some particular time, after the decay of the initialtransients, a small perturbation is made to the displacement. We can then compare thephase trajectories of the original and the perturbed motions. In non-chaotic motionsthese should be virtually indistinguishable. In chaotic motions there should be a largeeffect.

You should now attempt the exercises

1.8 Exercises

You are going to investigate the properties of the non-linear oscillator using parametersin the range

0 < F0 < 1000.05 < r < 0.40.9 < ω < 1.1

You will use an existing program chaos fourier which solves the differential equations,produces a displacement-time plot, a phase plot and a plot of the (magnitudes of the)Fourier spectrum.

Page 15: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

1.8 Exercises 15

In the Fourier plot, the large ’tics’ on the horizontal axis occur at multiples of ω the forcefrequency.

You will only need to make minor modifications to this program.

(i) [6 marks]Download the program chaos fourier.f95.Choose a value for ω and a value for r in the above ranges, record your choices andenter these values into the main program.Make an independent choice: Resist the urge to make the same choice as anothermember of the class.(a) Choose a small enough value for F0 that your system has essentially one fre-

quency. Confirm that:• the phase plot is elliptical;• the displacement is sinusoidal;• the perturbations have (almost) no effect. Visual confirmations are sufficient.

(b) Increase the size of F0 until harmonics start to appear in the Fourier spectrum.Confirm that:• the phase plot is no longer elliptical;• the displacement is periodic but no longer sinusoidal;• the perturbations have (almost) no effect.Visual confirmations are sufficient.

(c) Increase the size of F0 until sub-harmonics start to appear in the Fourier spec-trum. Identify these sub-harmonics (that is, have you found period-doubling,period-tripling, ...) Confirm that:• the phase plot is more complicated than before;• the displacement is periodic but with a greater period;• the perturbations have (almost) no effect.Visual confirmations are sufficient.

(d) Increase the size of F0 until a continuum of frequency components start to appearin the Fourier spectrum. Confirm that:• the phase plot is extremely complicated;• the displacement is no longer periodic;• the perturbations have a large effect.Visual confirmations are sufficient.

(e) Check whether the numerical procedure is influencing the results. Using a theprevious value of F0 (ie that which produces chaos), halve the time step anddetermine whether the results change.

(ii) [3 marks]Using the same r and ω, scan through a range of force values and see if you canidentify another regions which show interesting behaviour.

(iii) [8 marks]Choose one of the regions of F0 you have identified in the previous section.Do a detailed study in the two-dimensional region defined by (r, F0), using 0.05 <r < 0.4 and some suitably region around your selected value of F0.

Page 16: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

1.8 Exercises 16

Produce a map of your chosen region identifying where it is exhibits the variouspatterns of behaviour identified above.

Page 17: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

Chapter 2

ASPECTS OF OBJECT-ORIENTEDPROGRAMMING

Version date: Tuesday, 7 March 2006 at 09:19

2.1 Objectives

In this chapter you will encounter concepts in object-oriented programming in Fortranand make use of these in the context of physics.

2.2 Object-Oriented Programming

In object-oriented programming we strive to model a real-world problem by using con-structs called objects that are closer to the problem than the data types normally providedby a compiler; and by specifying the operations that can be performed on these objects.

In Fortran95 such objects are called derived data types.

For safety internal details of the objects should be encapsulated, that is hidden and onlyaccessible through a well defined procedures. This is particularly so in large softwareprojects, that may involve many programmers and may need to be maintained over manyyears.

In Fortran95 the objects (derived data types) and the operations on these objects arepackaged in a module which may be used by other parts of the programme. This providesfor easier maintenance because all the code relating to the objects is localized rather thanscattered throughout the programme.

Consider the following portion of a module:

MODULE SpaceVectorMod! A module for SpaceVector and SpaceVector operationsUSE GlobalConstantsIMPLICIT NONETYPE :: SpaceVectorPRIVATEREAL (KIND=DP) :: x

17

Page 18: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

2.2 Object-Oriented Programming 18

REAL (KIND=DP) :: yREAL (KIND=DP) :: z! The 3 private components of the SpaceVector

END TYPE SpaceVector

.

.END MODULE SpaceVectorMod

In this module we define an object which is a space (3D) vector. This has three compo-nents but these have been declared private and so are not directly accessible outside themodule.

To make use of space vectors in another programme segment we could do the following:

PROGRAM TestVectorModsUSE SpaceVectorModIMPLICIT NONE

TYPE (SpaceVector) :: A, B, es_prime(3)...END PROGRAM TestVectorMods

The variablesA andB are of type SpaceVector and es prime(3) is an array of SpaceVec-tors.

We want to be able to perform a variety of operations on SpaceVectors: assignment;addition; subtraction; multiplication and division by a scalar; scalar product; vectorproduct; etc.

The following example shows how a vector product is defined in this module :

INTERFACE OPERATOR(.CROSS.)MODULE PROCEDURE VectorProduct

END INTERFACE...FUNCTION VectorProduct(A,B)IMPLICIT NONETYPE (SpaceVector) :: VectorProductTYPE (SpaceVector), INTENT(IN) :: A, B

VectorProduct%x = A%y*B%z - A%z*B%yVectorProduct%y = A%z*B%x - A%x*B%zVectorProduct%z = A%x*B%y - A%y*B%x

RETURN

END FUNCTION VectorProduct

The interface defines the operator we use to denote the vector product and the functiontells the computer how to work this out. However we shall see later that the function

Page 19: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

2.2 Object-Oriented Programming 19

itself is hidden from users of the module. A user works out a vector product, for example,by

A = B .CROSS. C

As another, and more complicated, operation example consider multiplication of a vectorby a scalar:

INTERFACE OPERATOR(*)! * is used to indicate multiplication by a scalar (which must! have KIND=DP)MODULE PROCEDURE DP_Times_Vec, Vec_Times_DP

END INTERFACE...FUNCTION DP_Times_Vec(A, B)! Scalar times a VectorIMPLICIT NONEREAL (KIND=DP), INTENT(IN) :: ATYPE (SpaceVector), INTENT(IN) :: BTYPE (SpaceVector) :: DP_Times_Vec

DP_Times_Vec%x = A*B%xDP_Times_Vec%y = A*B%yDP_Times_Vec%z = A*B%z

RETURNEND FUNCTION DP_Times_Vec..FUNCTION Vec_Times_DP(A, B)! SpaceVector times a scalarIMPLICIT NONEREAL (KIND=DP), INTENT(IN) :: BTYPE (SpaceVector), INTENT(IN) :: ATYPE (SpaceVector) :: Vec_Times_DP

Vec_Times_DP%x = A%x*BVec_Times_DP%y = A%y*BVec_Times_DP%z = A%z*B

RETURNEND FUNCTION Vec_Times_DP

Here we see that the same operator * is used to describe two distinct operations: a scalartimes a vector and a vector times a scalar. This is called operator overloading. Againthe particular functions will be hidden from, and so cannot be changed by, the user. Thishiding can be achieved by

PRIVATE: Vector_Product, DP_Times_Vec, Vec_Times_DP

These functions would then not be directly available outside the module.

Page 20: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

2.2 Object-Oriented Programming 20

In the jargon of object-oriented programming the object plus the allowed operations onthat object constitute a class. So the above module defines a SpaceVector class.

Inheritance, in the most general sense, can be defined as the ability to construct morecomplex (derived) classes from simpler (base) classes in a hierarchical fashion. Gen-erally, the base class contains the properties (meaning data and procedures) which arecommon to a group of derived classes. Each derived class can then modify or extendeach of these for its own needs if necessary.

As an example, we use the SpaceVector class to define a SpaceTimeVector class. Thisis done in a module SpaceTimeVectorMod. The objects here are (four-dimensional)space-time vectors.

Now attempt exercise 1.

The purpose of dynamic dispatching or run-time polymorphism ( don’t you just lovecomputer science jargon!) is to allow one to write generic or abstract procedures whichwork on all classes in an inheritance hierarchy, yet produce results that depend on whichobject was actually used at run-time.

Examples of this already occur within Fortran. For example the READ and WRITEprocedures work with a range of variable types.

To illustrate the concept of creating a generic procedure consider the following: In themodule SpaceVectorMod we have a subroutine RotateSpaceFrame which operates on3 basis space-vectors and in the module SpaceTimeVectorMmod we have a subroutineRotateSpaceTimeFrame which operates on 4 basis space-time vectors. Since these areconceptually similar it would be convenient if we could refer to these by the same name.This could be achieved by inserting the interfaces

INTERFACE RotateFrameMODULE PROCEDURE RotateSpaceFrame

END INTERFACE

in SpaceVectorMod; and

INTERFACE RotateFrameMODULE PROCEDURE RotateSpaceTimeFrame

END INTERFACE

in SpaceTimeVectorMod.

RotateFrame should then work with space-vectors or with space-time vectors.

In practice, if we operate it on space-vectors it will actually call RotateSpaceFrameand if we operate it on space-time vectors it will call RotateSpaceTimeFrame but theprogrammer using these modules does not need to know this.

Now attempt exercise 2.

In the final exercise you are going to use the space-time vector module and its proceduresto solve some relativity problems. You should familiarize yourself with the subroutine

Page 21: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

2.3 EXERCISES 21

LorentzTransform(e rf1, e rf2, v over c)

in which e rf1 are the 4 basis vectors of the original reference frame and e rf2 are thefour basis vectors of the transformed reference frame. V over c is the relative velocityof the reference frame (divided by c). That is, it is the velocity of reference frame 2relative to reference frame 1.

Now attempt exercise 3

2.3 EXERCISES

1. [6 Marks]

Download the program OO Prog.f95. This contains two modules and some remnantsof my original testing procedures. The initialization procedures define the (space) basisvectors−→es1,−→es2,−→es3 (written in the programme as es(1), es(2), es(3)) and the space-timebasis vectors e0 e1, e2, e3 (written in the programme as e(0), e(1), e(2) and e(3))

Run the program and check that is operating correctly.

Define a space-vector by A = ax*es(1)+ay*es(2)+ay*es(3) where es(1:3) are the threebasis vectors defined when the module is initialized.

Try to evaluate the components of A directly by using A%x etc. Then try using thecomponent function:

CALL SpaceVectorComponent(A, es, A component)

Where A component is a three element array which holds the components of A

Modify the program to test ALL operations (except the frame rotations) on space andspace-time vectors.

2. [6 Marks]

Modify the program to test the operation of the two frame rotation subroutines. ChooseTWO simple rotations so that you can calculate the results easily.

Modify the program by creating a generic RotateFrame subroutine that will operate oneither space-vectors or on space-time-vectors. Test your new subroutine and record theresults

Make the original rotation subroutines PRIVATE and check that you can no longer usethem in the main program.

Modify the program by creating a generic Get Component that will operate on eitherspace-vectors or on space-time-vectors. That is, it performs SpaceVectorComponent onspace-vectors and performs SpaceTimeVectorComponent on space-time vectors. Testyour new subroutine and record your results.

Make the original component subroutines PRIVATE and check that you can no longeruse them in the main program.

Page 22: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

2.3 EXERCISES 22

3. [5 Marks]

Proper lifetime

In a particular experiment with π+ mesons the particles move (in the laboratory frame)with a speed 0.9978c. The mean lifetime measured in this laboratory frame is 2.70 ×10−7s. Determine the proper mean decay time of these particles.

Solve this problem as follows: Take the basis vectors e(0:3) to be the laboratory frame.Define a space-time displacement vector D that specifies the displacement of a mesonwhich has the mean lifetime. Find (using the Lorentz transformation) the basis vectorsin a reference frame which moves with this meson. The time-like component of D inthis reference frame is the proper decay time. The space-like component should be zero:The reference frame is moving with the particle.

Twin Paradox

We take an ideal case in which the stay-at-home twin is in an inertial reference frame.That is we neglect the (small on astronomical scale) motion of the earth. We also assumea simple path for the spaceship in which it moves at constant speed V for a certain timeand then exactly reverses that speed to return to its initial location.

Use the program procedures to determine the age difference if the total time of the flightmeasured from the inertial frame (the earth) is 10 years and the spaceship speed is V =±c/4. Define the three displacement vectors OP, OQ and QP. Check that these are alltime-like displacements using the function IsTimeLike(A) and evaluate the three lengthsusing the function SpaceTimeVectorLength(A). Hence determine the age difference.

Page 23: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

Chapter 3

QUANTUM STATISTICS: Application ofNumerical Integration

Version date: Wednesday, 20 February 2008 11:14

3.1 Objectives

In this chapter you are provided with a complete efficient Fortran function subprogramGAUSSR(F, a, b, prec, err) which integrates a function F , provided by the user, betweenthe limits a and b to a an accuracy specified by prec.

In the first few exercises you will carry out some test cases to check that the subprogramgives the answers that you would expect. Then you will use the subprogram to investi-gate the temperature dependence of the heat capacities for gases of (a) fermions and (b)bosons. Your results for the Fermi gas relate to the electronic contribution to the heatcapacity of metals: you should be able to show that this is small and that it varies linearlywith temperature at small T . For the Bose gas you should be able to demonstrate thatthe temperature derivative of the heat capacity is discontinuous at a critical temperature:There is a ‘lambda’ phase transition.

3.2 The program

The program Gauss test.f95 is on the Physics Intranet page. You should download thisand make a working copy (with a different name).

The program units are:

• MODULE Gaussian Integration: this you may regard as a ‘black box’ routine froma programming library. In the first few exercises you will check that it performscorrectly.

• MODULE Transfer data: not used initially but it will be used later as a means oftransferring data from programme section to another.

• The main program, Gauss Test which carries out two integrations for simple func-tions f1(x) = x + x3 and f2(θ) =sin2(θ) respectively. These can easily be checked.

23

Page 24: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

3.3 The Fermi gas 24

As well as providing a check on the procedure, this illustrates how to use the Gaus-sian integration module.

• The function subprograms.

Look at the provided program, paying particular attention to the way in which the dif-ferent units are linked as this involves some features of FORTRAN 95 that may be newto you. The function to be integrated (F) appears in the argument list of the GAUSSR.

The recommended way of declaring the function argument is to use an interface block– the section between INTERFACE and END INTERFACE. The same interface blockalso appears in the main program and here we need separate blocks for each of thefunctions involved (f1, f2, et cetera). This ensures that each subprogram element knowsthe properties of the function subroutine.

Now do Exercise 1 at the end of the chapter

3.3 The Fermi gas

The Fermi-Dirac distribution function for a non-interacting particle is

fFD(ε, µ, T ) =1

exp [(ε− µ) /kT ] + 1(3.1)

where ε is the energy of a particle, µ is the chemical potential and T is the temperature.This gives the probability density for the particle to have this energy. The total energyof the Fermi gas is

U (µ, T ) =

∞∫0

εD (ε) fFD(ε, µ, T ) dε (3.2)

where the number of states with energies between ε and ε+ dε has been written as:

D (ε) dε =

(V

2π2

)(2m

~2

)3/2

=3

2ε−3/2F

√ε dε (3.3)

The second form follows from the relation for the Fermi energy

εF =~2

2m

(3π2N

V

)=

~2

2m

(3π2 n

)2/3 (3.4)

The Fermi energy, is the chemical potential at T=0.

To find the heat capacity we need to know how U(T ) varies with temperature;

CV = (∂U/∂T )V (3.5)

.

Page 25: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

3.3 The Fermi gas 25

A problem that has to be addressed is that µ varies with temperature so the first stage ofthe calculation is to determine this temperature dependence. We do this by determiningthe number of particles. This is given by

N =

∞∫0

D(ε) fFD(ε, µ, T ) dε =V

2π2

(2m

~2

)3/2∞∫

0

√ε

exp {(ε− µ)/kT}+ 1dε (3.6)

This number is fixed and so we get the same value for any temperature including T = 0.In the case of T = 0, the final integral is simply

εF∫0

√ε dε =

2

3(εF )3/2

You should be able to explain why this result is so!

Thus at any temperature T the chemical potential µ must be have a value to ensure that

∞∫0

√ε

exp {(ε− µ)/kT}+ 1dε =

2

3(εF )3/2 .

This can be expressed more conveniently by using the following scaled variables:

ε = y2kT ; kT = tεF µ = ηkT = ηtεF ; (3.7)

Then the expression for η (the scaled chemical potential) becomes

∞∫0

y2

exp (y2 − η) + 1=

1

3t−3/2 (3.8)

There is no neat expression for this integral so we evaluate it numerically. For Gaussianintegration it is good practice to choose integrands that have no singularities. This is thereason for using the substitution ε = y2 kT rather than the more obvious ε = y kT . Thelatter substitution would have yielded a square root singularity in the integrand.

For a chosen value of t (i.e. T ) we have to find the value of η (i.e. µ/kT ) which makesthis equation correct.

This could be done by guessing a value for η for the chosen t; evaluating the integralnumerically and comparing with the required value of 1

3t−3/2; and then refining the guess

and so on until you get satisfactory agreement.

It can be shown that in the limit t→ 0, µ = η × t→ 1 and that for larger t η × t is lessthan 1. Hence we can start the search from η = 1/t and progressively reduce η.

Page 26: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

3.3 The Fermi gas 26

Notice that in the programs η is written as eta.

As a first stage in solving the problem, you should adapt the given program so that youinput a value for the reduced temperature tand then calculate the above integral for afew values of η. See if you get near to the required solution. Clearly you must enterthe appropriate FUNCTION procedure and the main PROGRAM will have to have linesasking for values of t and η. You also need to transfer these values for t and η into theFUNCTION. This is where MODULE Transfer data comes into play. All that is neededis to add a line

USE Transfer_data

at the start of the main PROGRAM and at the start of FUNCTION f(x). (In general thiswould appear in all program units that share the data.)

3.3.1 Infinite-range integrals

In theory the upper limit of the integral is infinity: In practice, we have to choose asuitable upper limit. We do this by choosing a value beyond which the contribution tothe integral is negligible. In order to do this we need some knowledge of the shape ofthe integrand. In this case the integrand decays rapidly for y2 − η � 1 A suitable valuecan be found by setting the argument of the exponential, (y2 − η), to be around 40: theintegrand is then about∼ 7×10−15. (I have assumed here that η is not very large.) Thereis little point in choosing a value larger than this this because the relative accuracy of thecomputer arithmetic (using kind 2) is about 2×10−16.

There is also a problem that there is a maximum value of an exponential argument thatthe computer can handle (about 700 using kind 2).

To use the value of 40 you need a line in your program like

b = SQRT(40.0_DP + eta)

where b is the upper limit of the integration range.

Now do Exercise 2 at the end of the chapter

The next stage is to introduce automated search for the correct value of η for each of arange of temperatures. A program Fermi.f95 is provided on the Physics Intranet page.This loops over values of t between just above 0 and 1.5. You will have to introduceyour new FUNCTION f(x) to make it run properly.

Now do Exercise 3 at the end of the chapter

The final stage of this exercise on the Fermi gas is to make some fairly minor additionsto the program to calculate the energy of the N particle Fermi gas as a function oftemperature. Using the dimensionless variables used in the above integration gives

Page 27: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

3.4 Bose-Einstein condensation 27

U(T ) = 3NεF t5/2

∞∫0

y4

exp {y2 − η}+ 1dy (3.9)

.

I introduce a dimensionless energy

u(t) =U(T )

NεF= 3 t5/2

∞∫0

y4

exp {y2 − η}+ 1dy (3.10)

The integral may be calculated within your development of Fermi.f95 by using the Gaus-sian Integration module again (as a final step within the loop over temperatures). In thenext Exercise you will compare the full numerical results you obtain with the low tem-perature approximation referred to in Exercise 2.

u (t) ∼=3

5+π2

4t2.

Now do Exercise 4 at the end of the chapter

3.4 Bose-Einstein condensation

We now consider a parallel study of the Bose gas.

For a gas of N non-interacting bosons, the counterpart of the Fermi-Dirac distributionis the Bose-Einstein distribution function:

fBE(ε;µ, T ) =1

exp {(ε− µ)/kT} − 1(3.11)

and the density of states no longer includes the spin-degeneracy factor of 2:

D(ε)dε =V

4π2

(2m

~2

)3/2√ε dε.

The minus sign in the numerator has a significant effect. The function must be positiveand so the chemical potential µ must be negative:

µ ≤ 0 (3.12)

The expression for the number of bosons is

N =

∞∫0

D(ε)fBE(ε;µ, T ) dε (3.13)

Page 28: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

3.4 Bose-Einstein condensation 28

If, as before, we use this relation to determine µ as a function of temperature, we findthat µ increases as T decreases and reaches zero at a particular temperature TC – thecritical temperature.

The formula for this critical temperature is

N =

∞∫0

D(ε)fBE(ε;µ = 0, T = TC) dε (3.14)

As the temperature is lowered below TC the chemical potential remains at zero (its max-imum value!) but the particles split into two groups.

A finite number N0 condense into the lowest energy state – this is possible becausebosons are not restricted by the exclusion principle as are fermions.

The number NE = N − N0 (– E for energetic!) of particles with non-zero energy canbe determined by using the above formula but with T < TC :

NE =

∞∫0

D(ε)fBE(ε;µ = 0, T ) dε T < TC (3.15)

Only these particles contribute to the energy and hence to the specific heat.

I will use dimensionless variables as before:

ε = y2kT ; µ = ηkT ; t = T /TC (3.16)

The equation for the critical temperature is

N =V

2π2

(2mk TC

~2

)3/2∞∫

0

y2

exp(y2)− 1dy =

V

2π2

(2mk TC

~2

)3/2

I2

where we have used the notation, I2 =∞∫0

y2

ey2−1dy. You should have calculated this

value.

This can be re-written as

TC =~2

2mk

(2π2N

I2V

)2/3

Page 29: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

3.4 Bose-Einstein condensation 29

3.4.1 t > 1

For t > 1 (that is T > TC the formula for determining the chemical potential is

∞∫0

y2

exp (y2 − η)− 1= I2 t

−3/2 (3.17)

In this case it can be shown that for t ≤ 1, η = 0 and for t > 1 η is negative. Hencea search procedure for η can start from η = 0 and progressively decrease this until asuitable value is found.

The energy in a dimensionless form can be written as

u(t) =U

N kTC=t5/2

I2

∞∫0

y4

exp (y2 − η)− 1(3.18)

where the value of η found from (3.17) has to be used.

3.4.2 t < 1

For t < 1, that is T < TC the fraction of particles which have non-zero energy is

NE

N= t3/2 (3.19)

This fraction contributes to the energy which (in the same units as above) is

u(t) =U

N kTC= t5/2

I4I2

(3.20)

where I have used I4 to denote

I4 =

∞∫0

y4

exp (y2)− 1(3.21)

You should have calculated this value previously.

Now attempt Exercise 5 at the end of the chapter

Page 30: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

3.5 EXERCISES 30

3.5 EXERCISES

Exercise 1 [4 Marks] Run the program Gauss test.f95 (or your working copy) as itstands and check that the two integrations are correct.

Modify the program and verify the following 3 results, which are standard integrals:

∞∫0

x3

(exp(x)−1)dx =

1

15π4 ;

∞∫0

1exp(x)+1

dx = ln (2)

∞∫0

x2 exp(x)

(exp(x)+1)2dx = 1

6π2 ;

You cannot of course set the upper limit of the integrals to infinity. You must set it toa high enough value for further increases to be of no consequence but not so high thatinaccuracies are introduced by making the integration intervals unnecessarily large.

You should choose a suitable upper limit for each case taking into account the bestrelative precision that can be achieved using kind 2 (or double precision) is about 2 ×10−16.

Use the program to evaluate the following integrals:

I2 =∞∫0

y2

exp(y2)−1dy

I4 =∞∫0

y4

exp(y2)−1dy

Of course, you again need to choose and justify a suitable upper limit in each case.

Record these values: you will need them later.

Exercise 2 [3 Marks] Adapt your copy of Gauss test.f95 so that it calculates the inte-gral in (3.8) for values of η that are read into the program. Carry out some runs of thisprogram keeping your choice of t fixed and varying η so that you get a value close to13t−3/2. Repeat for a few other choices of t (e.g. t = 0.1, 0.3, 0.5).

Exercise 3 [2 Marks] Explain how the calculations are organized in Fermi.F95, inparticular how the different temperatures are chosen and how, for each of these, thecorrect value of the chemical potential is estimated.

Supply the required FUNCTION f to Fermi.f95 and run the program.

Plot η t (= µ/εF ) versus t.

Page 31: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

3.5 EXERCISES 31

Exercise 4 [3 Marks] Produce a table and a graph displaying u(t) for a range of(scaled) temperatures t with values obtained (a) by numerical integration and (b) fromthe low temperature approximation result. Hence find the range of temperatures forwhich the approximation is reasonable.

Produce a corresponding table and graph for the (dimensionless) specific heat du (t) /dt.

Exercise 5 [5 Marks] Adapt the program Fermi.f95 (and rename it!) so as to deal withthe Bose-Eintein condensation.

In order to do this you will have to change the functions you introduced for the FermiGas and also the starting value for η. This starting value should be set to 0. The startingvalue for the temperature t should also be set to just greater than 1.

Find and tabulate η t for a set of equally spaced values of the dimensionless temperaturet = T/TC covering the range t = 1 to t = 2.

Produce tables and graphs displaying u(t); the (dimensionless) specific heat du (t) /dt;and the derivative of the specific heat d2u (t) /dt2 for a set of equally spaced values of tbetween t = 0 and t = 2. The results for t < 1 are given by equation (3.20). You shouldexplain your method of obtaining the derivatives.

Page 32: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

Chapter 4

THE RANDOM WALK

4.1 OBJECTIVES

The random walk is an idealisation of diffusive motion. It also forms the basis for manyproblems in statistical physics. Examples range from the movement of oil through shaleto a description of the shape and extent of polymer chains. We start by considering therandom walker and then develop the ideas to study two applications.

4.2 THE RANDOM WALKER

Brownian motion was first studied over 100 years ago. It is one of the many diversediffusion type problems that appear in Physics. Generally, what one is trying to describeis the behaviour of a particle that is moving randomly through a medium that is itselfin some way disordered. The random walker is an idealisation of the phenomenon thatallows us to understand the underlying principles.

The random walk problem can be stated very simply: if a walker starts from a particularpoint and takes a series of steps of unit length each in a random direction, how faron average will he have travelled from the origin after N steps? Often to make thedescription more colourful, text-books use the analogy of a drunkard making an erraticpath home from the pub. Evidently the average distance is zero because he is allowedto go forward as well as backward, but it is of interest to ask about the mean squaredistance moved.

The theoretical result is easily obtained. Suppose that after n steps his vector positionwith respect to the starting point is Ln. Each step is of unit length and we will representthe step that takes him from Ln to Ln+1 by s. Then

−→L n+1 =

−→L n +−→s

Squaring and noting that s2 = 1, we get

L2n+1 = L2

n + 1 + 2−→L · −→s

32

Page 33: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

4.3 The Random Walker on the Computer 33

If each step really is in a random direction then, averaged over lots of walks, the meanof the dot product is zero and

< L2n+1 >=< L2

n > +1

Thus the mean square displacement increases by 1 unit at each step and so after N steps

< L2N >= N

So, the root mean square distance travelled in N steps, defined as

LrmsN =√< L2

N >

is given by the square root of N

LrmsN = N1/2

If the steps in the walk are not of unit length or if they are of variable length or, indeed,even if there are on average more forward steps than backward ones, then the squareroot behaviour still occurs. The above rule is merely replaced by

LrmsN = αN1/2

where α is a constant that depends on the details of the random walk process.

It is important to know the constant α if we want to estimate how long it takes for areal diffusion process to take. However it is the exponent 1

2that contains the underlying

physics - it tells us that a diffusion process is occurring. It is also important for thedrunkard. He knows that, if he moves to a house that is twice as far away from thepub, he is going to take four times as long to get home (it is the 1

2−power law that

distinguishes drunkenness from the linear behaviour of sobriety).

4.3 The Random Walker on the Computer

These are some of the basic facts about the idealized random walker. In many physicalsituations, additional constraints on the motion are present. These will prevent an ana-lytic calculation and we have to use computer simulation. We would like first to see howto set up a program to describe something that we know the answer to. The programsqwalker.f95 simulates a random walk in two dimensions. It has been simplified so thateach move is a step to the left, right, up, or down. In other words, it simulates walks ona square lattice.

Run the program in graphical mode (answer y to the first question). You can choose thenumber of steps and also repeat the process with the number of walkers of your choice.

Page 34: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

4.4 THE RANDOM WALKER AND PERCOLATION 34

The open circle indicates the starting point and the filled circles show where each walkerends up. Make sure you understand the random walk simulation in the program. Thecode for doing it is quite short (most of the program is for producing the graphics – youdo not need to be concerned with the details of that).

⇒ Go to Exercise 1

4.4 THE RANDOM WALKER AND PERCOLATION

There are many problems in physics where the properties of the medium itself affect theprogress of the particles diffusing through it. Particles may be created or destroyed orthere may be impenetrable barriers. A neutron moving in a reactor may be absorbed,slowed down (moderated) or new ones may be created (fission).

Sometimes electrical conduction in solids is via electrons hopping from one defect toanother. To get transport from one side of the sample to the other, we need at least onecontinuous path of these defects across the system. When enough defects have been putin to form a contiguous path one has reached what is called the percolation threshold.

Similar considerations apply to the passage of a liquid through a porous material withthe pores needing to form a continuous path for percolation to occur.

Transport in such systems as these can be simulated by our random walker moving on asquare lattice. The walker is allowed to visit certain of the sites but not the remainder.The proportion can be varied to study the properties of percolating systems. To beprecise let p denote the fraction of the sites that the particle is allowed to visit (for p = 1,all sites can be visited; if p = 0, none can). There is a specific value of p (the percolationthreshold: call it pc), and if p < pc no contiguous path exists across an infinite lattice.

Applications for percolation theory have been claimed in even wider areas than thosementioned. The spread of forest fires and the transmission of diseases are related to thedensities of tree planting and populations respectively. Life is safer if the densities arebelow a percolation threshold!

It is relatively straightforward to modify the program developed in the Exercise 1 to thepercolation problem. Each step of the random walk was on a lattice (positions defined bya pair of integer coordinates i,j relative to the origin). Suppose we define an integer array– call it lat(i, j). If the walker is allowed to alight on site (i, j), we set lat(i, j) = 1; ifthe site is forbidden, we set lat(i, j) = 0. The random number generator can be appliedinitially (before the walks start) to put a 1 on a fraction p of the sites and a 0 on theremainder. For each step of the random walk, a choice from 4 directions is selected –and then one determines from the lat register whether to allow the walker to proceed.

What do we expect to happen? Initially, as p decreases, diffusive motion will still occuralthough with some impediment. We expect the exponent of 1

2will still appear but the

prefactor α will get smaller. As we move towards pc deviations from this behaviour willoccur and, below pc, motion becomes more restricted.

⇒ Go to Exercise 2

Page 35: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

4.5 THE SELF-AVOIDING WALK (polymers or spaghetti) 35

4.5 THE SELF-AVOIDING WALK (polymers or spaghetti)

Think of a single strand of spaghetti in warm water. It is neither fully stretched norcollapses into a ball. What is the average end to end distance? We can ask similarquestion about polymer chains in a dilute solution. Each link in a chain is like a step inthe random walk problem, but now there is a difference – excluded volume. The walkcannot go back on ground already covered because that is occupied by the part of thechain that was formed earlier in the walk. We have to deal with self-avoiding walks(SAWs).

Clearly one modification from the random walk construction is the prohibition of a back-ward step (because of the SAW condition). So for each step there are 3 possibilitiesinstead of 4.

There is also another restriction. A step cannot be taken in a direction which would hitpart of the chain already formed.

A simple algorithm for constructing a model chain is:

• Start at the origin (0,0).

• Take the first step to (0,1). The choice of the first step is arbitrary (there are 4symmetrically equivalent possibilities).

• Choose 1 of the 3 possibilities for the next step.

• Repeat but note that from the 4th step on there is a chance of hitting the existingchain.

• If at step N + 1, a hit occurs with the existing chain, terminate the algorithm andrecord the creation of a chain of length N. Ignore the last disallowed step. Terminationhas to occur to define a chain length.

In the exercise, you are asked to investigate the rms end-to-end separation as a functionof chain size N. Let us generalize the random walk relation and write

LrmsN = αNγ

For the random walk, γ was 12, but we do not wish to make prior assumptions here. We

can take logarithms in the above equation and write

lnLrmsN = lnα + γ lnN

A plot of ln(LrmsN ) against ln(N) should give a straight line with gradient γ. Hence wecan determine γ.

There is some important physics that you can investigate. γ is a quantity that exemplifiesuniversality. Whereas α depends on model details, γ is something much more general.The value it takes (which is not 1

2, by the way) depends only on the fact that you are

trying to form a polymer-like object in 2 dimensions (on a plane). The details of the

Page 36: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

4.5 THE SELF-AVOIDING WALK (polymers or spaghetti) 36

algorithm (like the step length or only 90o or 180o angles) do not matter. γ then hasfundamental significance – it is associated with the dimensionality of space rather thanmodel details. Most universal exponents depend on dimensionality and rather little else.An exception is γ = 1

2for the simple random walk; it has that value in all dimensions (it

is super-universal) and this is rather unusual.

⇒ Go to Exercise 3

EXERCISES

1. [ 5 Marks ]

The object of this exercise is to test the 12−power law that we expect for a random walk.

Write some code to work out the mean square displacements in the x and y directions.You will be averaging over all walkers, and you will need to store your results in arraysso that you have the mean values for N steps where N ranges from 1 to nstep. Thesum of the squares for the two directions gives you < L2

N > and, if you print out theresults, you should be able to see by inspection that it is fairly close to N for all valuesof N. Graphics are slow and it is suggested that you do not display the pictures duringthe ‘serious’ calculations.

If you now write your results for < L2N > and N to a file, you can use them as input to

a plotting routine, and then do a straight line fit. You can use Excel, for example.

To get good results, average over a large number of walkers (say 10000), and go up to500 steps (more if you like).

2. [ 6 Marks ]

Start with the program you developed in the previous exercise. Define an integer array

lat(−nstep : nstep,−nstep : nstep).

It is extremely unlikely that you will need array bounds as large as this – but it is safe.Define p ( simplest if you read it in). Use the random number generator to put a 1 on afraction p of the sites and 0 on a fraction (1− p). The simplest way method is to put a 1everywhere first, and then replace a fraction (1− p) of them with a 0. Ensure there is a1 on (0, 0) otherwise the walker has nowhere to start. Now modify the stepping part ofthe program so that the walker remains where he is if his next step would take him ontoa forbidden site. Even if the walker cannot move increase the clock by 1 tick (i.e. add 1to the step counter). Check that the program reproduces previous behaviour if p = 1.

We should put one more detail into the program before any ‘production’ runs are at-tempted. The procedure above defines a single environment. We should average overnot only many walks but over many environments as well. This can be done with ajudiciously placed do loop, so that when the walkers have finished their trip, they arerestarted in a new environment.

The program has more to do than in the previous exercise and consequently will beslower. You have also got a lot of disorder in the problem and so you should averageover both walks (> 100) and environments (> 100) and, if necessary, compromise onthe total length of the walks (N = 200 should suffice). Averaging over environments is

Page 37: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

4.5 THE SELF-AVOIDING WALK (polymers or spaghetti) 37

probably more important than averaging over walkers.

Use your program to study the behaviour. Plot the mean square displacement as a func-tion on N for several values of p. Make a plot of α as a function of p (you will be ableto do this only over a limited range of values, because it is only defined while the meansquare displacement remains proportional to N ). Try to deduce the value of pc.

3. [ 6 Marks ]

Run the program saw.f95. It generates self-avoiding walks. You can input the numberof steps and the number of walkers. The co-ordinates of the chains are printed to a file.The message ‘repeated site – chain complete’ indicates a complete chain. Make sureyou understand what the program does. Choose a fairly small number of walkers (say< 10) for the moment – otherwise you will produce an indigestible amount of data.

Now add a few lines of code to determine how many chains of a certain length areproduced. Specifically: if you have say 1000 walkers, how many chains of length 10(also 20 30, 40 50 100) or longer do you generate? You are advised to delete existingwrite statements before running. Do not do a statistical analysis of this. The purpose ofthis preliminary question is to give you a rough idea of the size of the chains you will bedealing with.

Write some code to determine the average rms end-to-end distance (as a function ofchain length) of the chains you have generated. Note we are dealing only with completedchains; you also have to remember that there are different numbers of chains for eachchain size.

If you output the logarithms of the rms chain end-to-end separations against ln N, thenyou have data ready for a straight line fitting procedure from which you can determine γ.Adjust the number of chains generated until you get reasonable statistics for determiningγ. Aim to go up to about 40 in chain size and a large value for nwalker (50,000 perhaps).

Finally, you can very easily do a test of universality. Modify the program so that onlyleft and right steps are allowed and forward steps are forbidden. Fewer long chains willbe generated. You will not find many with N above about 30. Check to see whether γ isthe same as for the previous algorithm. Whether or not α is the same is not significantbut, because of universality, γ is expected to be unchanged.

Page 38: Computational Physics 2 - Reading · Fortran 95/2003 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-8526293-8 $35.00 Fortran 90 for Scientists and Engineers

4.5 THE SELF-AVOIDING WALK (polymers or spaghetti) 38