computational physics home pagefortran 90/95 explained by michael metcalf and john reid oxford...

93
Home Page Title Page Contents Page 1 of 91 Go Back Full Screen Close Quit Computational Physics Unit 3phss by Dennis Dunn Version date: Thursday, 12 June 2003 at 14:03

Upload: others

Post on 30-Apr-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 1 of 91

Go Back

Full Screen

Close

Quit

Computational Physics

Unit 3phss

by Dennis Dunn

Version date: Thursday, 12 June 2003 at 14:03

Page 2: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 2 of 91

Go Back

Full Screen

Close

Quit

ComputationalPhysics–Com

putationalPhysics

ComputationalPhysics–Com

putationalPhysics

ComputationalP

hysic

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 P

hysic

s–

Compu

tatio

nalP

hysic

s

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

tatio

nal P

hysic

s

Com

putational Physics–

Computational Physics

Com

putational Physics–

Computational PhysicsC

omputationalP

hysics–Computational Physics

Com

putationalPhysics–

Computational Physics

ComputationalPhysics–

Computational Physics

ComputationalPhysics–Com

putational Physics

Page 3: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 3 of 91

Go Back

Full Screen

Close

Quit

Copyright c©2003 Dennis Dunn.

Page 4: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 4 of 91

Go Back

Full Screen

Close

Quit

Contents

Contents 4

INTRODUCTION TO THE UNIT 5

1 INTRODUCTION TO FORTRAN 95, PART I 17

1.1 Objectives 18

1.2 Deadline 19

1.3 Introduction 20

1.4 Sample program 1: 21

1.5 Sample program 2: 25

1.6 Sample program 3: 28

1.7 Numerical Accuracy 31

1.8 Exercises 32

Page 5: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 5 of 91

Go Back

Full Screen

Close

Quit

2 INTRODUCTION TO FORTRAN 95, PART II 36

2.1 Objectives 37

2.2 Deadline 38

2.3 Arrays 39

2.3.1 Arrays and Sorting 39

2.3.2 Defined Types and More Sorting 43

2.4 Whole array expressions 45

2.5 Computational Techniques 49

2.5.1 Summations 49

2.5.2 Integration 50

2.5.3 Differentiation 51

2.6 Graphics 52

2.7 Exercises 58

3 EQUATIONS OF MOTION IN PHYSICS 60

3.1 Objectives 61

3.2 Deadline 62

3.3 The Numerical Methods 63

3.4 The forced damped oscillator 66

3.5 Exercises 69

Page 6: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 6 of 91

Go Back

Full Screen

Close

Quit

4 PLANETARY MOTION 72

4.1 Objectives 73

4.2 Deadline 74

4.3 Equations of Motion. 75

4.4 Conservation of Angular Momentum 76

4.5 Polar Co-ordinates 77

4.6 Numerical solution of equations of motion 78

4.7 Energy and Angular Momentum 79

4.8 Units 80

4.9 Initial Values 81

4.10 The Programme 84

4.11 Kepler’s Laws 86

4.12 EXERCISES 88

Index 91

Page 7: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 7 of 91

Go Back

Full Screen

Close

Quit

INTRODUCTION TO THE UNIT

Version date: Thursday, 24 April 2003

Page 8: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 8 of 91

Go Back

Full Screen

Close

Quit

Introduction

In this unit you will be taught techniques employed in computational science and, in particular,computational physics using the FORTRAN95 language. The unit consists of 9 ‘computer experi-ments’, each of which must be completed within a specified time (either two or three weeks). Each‘computer experiment’ is described in a separate chapter of this manual and contains a series ofexercises for you to complete. You should work alone and should keep a detailed record of thework in a logbook that must be submitted for assessment at the end of each experiment.

The Salford Fortran95 compiler will be used in this course, and this may be started by double-clicking on the Plato icon under the “Programming - Salford Fortran 95” program group. A “FTN95Help” facility is supplied with this software and can be found within the same program group. Thishelp facility includes details of the standard FORTRAN95 commands as well as the compiler-specific graphics features. All of the programs needed during this course may be downloaded fromthe Part III - Computational Physics page on the department’s web-server (www.rdg.ac.uk/physicsnet).

Page 9: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 9 of 91

Go Back

Full Screen

Close

Quit

Web Site Information

In addition to all the chapters and programs required for this course, there are links to other usefulsites including a description of programming style; a description of computational science in gen-eral and FORTRAN programming in particular; a tutorial for FORTRAN90; and a description ofobject-oriented programming.

Page 10: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 10 of 91

Go Back

Full Screen

Close

Quit

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.nasoftware.co.uk/fortran-plus/book.html£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 90/95 Explained

By Michael Metcalf and John Reid

Oxford University Press ISBN 0-19-851888-9

$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

Page 11: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 11 of 91

Go Back

Full Screen

Close

Quit

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.

Page 12: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 12 of 91

Go Back

Full Screen

Close

Quit

Logbooks

You must keep an accurate and complete record of the work in a logbook.The logbook is what isassessed. In the logbook you should answer all the questions asked in the text, include copies of theprograms with explanations of how they work, and record details of the program inputs and of theoutput created by the programs. On completion of each chapter you should write a brief summaryof what has been achieved in the project.

I am often asked what should go in the logbook. It is difficult to give a simple answer to this sinceeach computer experiment is different but as a guide you should have sufficient information forsomeone else

• to understand what you were doing and why; and• to be able to repeat the computer experiment.

Page 13: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 13 of 91

Go Back

Full Screen

Close

Quit

Unit Assessment

The logbooks must be submitted for assessment to the General Office by the specified deadlines.Late submissions will only be assessed in extenuating circumstances.

Guidelines on the assessment are given below.

Page 14: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 14 of 91

Go Back

Full Screen

Close

Quit

Late Submissions

10% of the total marksavailable for the piece of work will be deducted from the mark where thepiece of work is submitted up to one calendar week after the original deadline. Once this period haselapsed, a mark ofzerowill be recorded.

Page 15: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 15 of 91

Go Back

Full Screen

Close

Quit

Feedback

In addition to comments written in your logbook by the assessor during marking, feedback on theprojects will be provided by a class discussion and, when appropriate, by individual discussion withthe lecturer.

Page 16: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 16 of 91

Go Back

Full Screen

Close

Quit

Assessment Guidelines

This unit is assessed completely by continuous assessment. Each project (which corresponds to onechapter of the manual) is assessed as follows.

The depth of understanding and level of achievement will be assessed taking into account the fol-lowing three categories:

1. Completion of the exercises (0 – 17 marks)Completeness of the recordDescription and justification of all actionsFollowing the documented instructions, answering questions andperforming derivations etc.

2. Summary (0 – 3 marks)• Review of objectives• Summary of achievements• Retrospective comments on the effectiveness of the exer-cises

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

The total mark of a project cannot exceed 20. Unfinished work will be marked pro rata, unless thereare extenuated circumstances.

The marks awarded for the best 8 of the 9 computer experiments will collectively form the overall

Page 17: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 17 of 91

Go Back

Full Screen

Close

Quit

assessment for this unit.

If you are unable to attend the laboratory session you should inform the Department Records Ad-ministrator (Mrs S A Moon) by telephone 8543 (0118 931 8543) or by email [email protected]

Page 18: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 18 of 91

Go Back

Full Screen

Close

Quit

Projects

Summer Term

• Introduction to Fortran 95 ; Part 1• Introduction to Fortran 95 ; Part 2• Equations of motion in physics• Planetary motion

Autumn Term

• Eigenvalues and Eigenvectors of Matrices: Application to the Vibrational Modes of LinearChains

• Random Processes• Numerical Integration: Application to some Problems in Quantum Statistics• Equilibrium and Temperature• Analysis of Waveforms OR Multilayer Dielectric Stacks OR The Random Walk

Page 19: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 19 of 91

Go Back

Full Screen

Close

Quit

Chapter 1

INTRODUCTION TO FORTRAN 95, PART I

Version date: Thursday, 24 April 2003

Page 20: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 20 of 91

Go Back

Full Screen

Close

Quit

1.1. Objectives

To introduce the basic elements of FORTRAN 95, such as procedures and control constructs,through sample programs and their descriptions. At the end of this chapter students should beable to write elementary programs and run them using theSalfordcompiler software.

Page 21: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 21 of 91

Go Back

Full Screen

Close

Quit

1.2. Deadline

12 noon Wednesday, 21 May 2003.

This is also the deadline for next project. That is, I will mark the first two projects together.Youshould aim to complete the project in two weeks.

Page 22: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 22 of 91

Go Back

Full Screen

Close

Quit

1.3. Introduction

For nearly fifty years FORTRAN has been the principal language of computational science. It wasintroduced by IBM in the 1950’s and called FORmula TRANslation and it transformed computing.As its name implies it was specifically designed for numerical tasks encountered in the physical andmathematical sciences, and the computational efficiency of the language makes it the language ofchoice for the majority of practicing physicists.

It has evolved over the years and the stages of evolution have been marked by various languagestandards: FORTRAN66 (in about 1966); FORTRAN77 (in about 1977); FORTRAN90 (in 1990);and FORTRAN95 (in 1995). The next version of the standard is already available in draft form:This will be called FORTRAN2000 and is expected to be released later this year (2003).

FORTRAN95 is currently regarded as the best language for most aspects of computational science,object oriented programming being the only area where it is not considered the best. For details seea report by the Computational Science Education Project ‘Fortran and computational science’ onwebsite http://csep1.phy.ornl.gov/pl/pl.html.

FORTRAN95 does contain most (but not all) elements of object oriented programming and alsoincludes many features which make it ideal for parallel processors.

In this first chapter we shall consider the basic elements of the language through sample programs,since it is only through its use that one learns the essential tools of programming. As you progressthrough the course you shall encounter further features of the language whilst reinforcing yourprevious knowledge. However the emphasis of this course is physics and how computational tech-niques provide a versatile tool for investigating physical situations, rather than simply the program-ming language itself.

Page 23: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 23 of 91

Go Back

Full Screen

Close

Quit

1.4. Sample program 1:

The first program is an example of translating a mathematical formula. Consider a triangle withsidesx, y andz. The area of a triangle is12base × height. If I take y as the base the formula forthe area can be written as

Area = 12yh

h = xsin(θ)cos(θ) = x2+y2−z2

2xy

The last part of this formula can be obtained by writing the three sides asvectorsx, y andz andusing the relations

z = x− yz • z = x • x + y • y− 2x • y

The following simple program calculates the area of a triangle whose side lengths are entered bythe user. You should note that this is (deliberately) a poorly written program because it does notcheck that that the inputs are valid. You will remedy this defect later.

PROGRAM Triangle

! Version Date: 19 April 2002

! This is a (deliberately) badly written program for determiningthe! area of a triangle given the lengths of the three sides.

! You will improve it

IMPLICIT NONEREAL :: a, b, c, Area

Page 24: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 24 of 91

Go Back

Full Screen

Close

Quit

WRITE(*, *) ’ Enter the lengths of the three sides’WRITE(*, *) ’ Check that they make a triangle ! ’READ(*, *) a, b, cArea = Triangle_Area(a, b, c)

WRITE(*,*) ’ Area of triangle is ’, AreaWRITE(*,*) ’ Press ENTER to stop’READ(*,*)STOP

CONTAINS

FUNCTION Triangle_Area(x,y,z)IMPLICIT NONEREAL :: Triangle_AreaREAL, INTENT(IN) :: x,y,zREAL :: theta, heighttheta = ACOS((x**2 + y**2 - z**2)/(2.0*x*y))height = x*SIN(theta)Triangle_Area = 0.5*y*heightRETURN

END FUNCTION Triangle_Area

END PROGRAM Triangle

The following points should be noted:

Language:The code is written using letters (with no distinction between upper and lower cases),numbers, and a few extra characters.

Commands:These have been written in capital letters for clarity, with user defined variables andtext in lower case. Specifically the program uses the following commands:

Page 25: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 25 of 91

Go Back

Full Screen

Close

Quit

PROGRAM Declares the main program unit, called ‘Triangle’ here.IMPLICIT NONE This means that all variables must be declared before they

are used, unlike older versions of the language.REAL This declares the list of variables following the colons to

be of real (ie floating point) type. Other common numeri-cal types are INTEGER and COMPLEX. A REAL numberis for example 1.35 or 1.46E-10 (=1.46×10−10); an IN-TEGER is 49 or 123456; a COMPLEX number is (1.345,1.25E-3). The variable names can be up to 32 characterslong starting with a letter, and may include numbers and(the underscore) but cannot contain spaces.

WRITE(*,*) Writes the following text, which appears inside invertedcommas, or the numerical values of the listed variables tothe default output device (the screen) using the default for-mat. Greater control of the format and output device ispossible by appropriately replacing the asterices.

READ(*,*) As above except the variables (in this case real numbers)are read in from the keyboard which is the default inputdevice.

STOP Halts the program.CONTAINS Indicates that the following segments of code (generically

called procedures) are used by the main program. Here thefunction TriangleArea(x,y,z) is the only procedure used.

FUNCTION Declares the start of the function.INTENT(IN) The following list of real variables are values used by the

procedure but not changed by it. The other possible at-tributes for INTENT are (OUT) and (IN OUT), and theirmeanings are obvious.

Page 26: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 26 of 91

Go Back

Full Screen

Close

Quit

ACOS Inverse cosine function.SIN Sine function.RETURN Return from the procedure to the main program, at the

point immediately following the call to the procedure.END Marks the end of the appropriate program unit.

A complete list of FORTRAN 95 commands is provided in theSalford FTN95 Help (LanguageOverview)program.

Procedures:The use of procedures greatly simplifies programs by making it obvious to the readerhow the program works. It also makes the program more failsafe by keeping the block of codethat performs a specific task packaged in one place. The procedure used here was the functionTriangleArea(x,y,z); ‘function’ means that the variable ‘TriangleArea’ itself takes a value. Notethe arguments (x,y,z) are dummy variable names; they do not have to be the same names (a,b,c)as those used in the main program that uses the procedure. However they do have to be the sametypes. Suppose a functionfunc is defined in a function subroutine to have variablesu, v andw andis used in a program asfunc(r, s, t) Thenr must be of the sametypeasu, s must be of the sametypeasv andt must be of the sametypeasw.

This makes procedures very versatile. They can be used several times within the main program,and very often they have been written elsewhere so that the user does not have to know exactly howthey work and can treat them like ‘black boxes’. Libraries of sophisticated procedures exist thatperform common tasks such as integrating functions, finding eigenvalues of matrices etc.

If you understand what you have read, you may now attempt the first exercise given at the end ofthis chapter.

Page 27: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 27 of 91

Go Back

Full Screen

Close

Quit

1.5. Sample program 2:

The second program is an even simpler example of formula translation. The program calculates thearea of circle with radius entered by the user:

! Version Date: 19 April 2002 DD

MODULE global_constantsIMPLICIT NONEREAL, PARAMETER :: pi=3.14159265358979324

END MODULE global_constants

PROGRAM RoundIMPLICIT NONEREAL :: Radius, Area, VolumeDO

WRITE(*, *) ’ Enter the Radius (negative to finish)’READ(*, *) RadiusIF (Radius .LT. 0.0) EXITArea = Circle_Area(Radius)WRITE(*,*) ’ Circle with Radius ’,Radius,&

’ has area ’, Area

! You need to write the function Volume and then remove the comment! symbol(!) from the following lines

! Volume = Sphere_Volume(Radius)! WRITE(*,*) ’ Sphere with Radius’, Radius,&! ’ has volume ’, Volume

END DO

Page 28: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 28 of 91

Go Back

Full Screen

Close

Quit

STOP

CONTAINS

FUNCTION Circle_Area(r)USE global_constantsIMPLICIT NONEREAL :: Circle_AreaREAL, INTENT(IN) :: rCircle_Area = pi*r**2RETURN

END FUNCTION Circle_Area

END PROGRAM Round

The new features that this program introduces are:

MODULE A module is a block of code that may already be compiledand which can be ‘used’ in other programs. It may be used tohold data and procedures. Here it is simply used to define pi,although other useful constants may be added to the module.

PARAMETER Defines the listed variables as being fixed in value through-out the program.

DO . . . END DO The segment of code between DO and the END DO com-mand will be repeatedly executed until (radius .LT. 0) is sat-isfied

Page 29: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 29 of 91

Go Back

Full Screen

Close

Quit

IF ( ) EXIT In this statement if the condition in brackets is true then theDO loop is terminated and control passes to the line afterthe END DO. In the condition .LT. means ‘less than’. Otherlogical conditions are allowed; .GT. means ‘greater than’..GE. means ‘greater than or equal to’, .LE. means ‘less thanor equal to’. .EQ. and .NE. are ‘equal to’ and ‘not equalto’ respectively. Alternative notation for these symbols isrespectively:<, >, >=, <=, ==, and/ =. Notice that thetest for equality is== and not=.

USE Use the modules listed; ‘globalconstants’ only here.! Comments are prefaced by ! These can be placed throughout

a program

If you understand what you have read, you may now attempt exercise 2 given at the end of thischapter.

Page 30: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 30 of 91

Go Back

Full Screen

Close

Quit

1.6. Sample program 3:

The following program is an example of theIF . . . THEN . . . ELSE control structure. The pro-gram takes three integers as input and indicates the number of different ways these three integerscould be written. If the three integers are all different then there aresixdifferent ways. For example:

(1, 2, 3) (3, 1, 2) (2, 3, 1) (1, 3, 2) (2, 1, 3) (3, 2, 1)

If two of the integers are the same then there arethreeways of writing them. If all three integersare the same then there is onlyoneway.

The program outputs the number of permutations possible for sets of three integers where the max-imum integer is specified by the user.

PROGRAM Permutations

! This program indicates the number of ways in which a set of 3 integers! can be written

! Version Date: 9 April 2003 DD

IMPLICIT NONEINTEGER :: i, j, k, n, perms

DOWRITE(*,*)’ Enter the maximum integer (less than ten) ’READ(*,*) nIF (n .LT. 10 .AND. n .GT. 0) EXIT

END DO

Page 31: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 31 of 91

Go Back

Full Screen

Close

Quit

DO i = 1, nDO j = 1, i

DO k = 1, jIF((i.EQ.j).AND.(i.EQ.k)) THEN

! This checks whether they are all equalperms=1

ELSEIF((i.EQ.j).OR.(i.EQ.k).OR.(j.EQ.k)) THEN

! This checks whether any two are equalperms=3

ELSEperms=6

END IFEND IFWRITE(*,’(3i5, i10)’) i, j, k, perms

END DOEND DOWRITE(*,*)’ Press return for next set ’READ(*,*)

END DOWRITE(*,*)’Press return to stop ’READ(*,*)STOP

END PROGRAM Permutations

The new features here are:

INTEGER Lists the variables which are integers. Note that these wholenumbers are stored exactly, whereas real variables are onlystored approximately. Single precision means real variablesare stored to about 7 decimal places accuracy, and doubleprecision stored to 14 decimal places.

Page 32: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 32 of 91

Go Back

Full Screen

Close

Quit

DO k=1, j The block of code between this command and its associ-ated END DO command is repeatedly executed, with theINTEGER counter k starting at one and incrementing byone on each loop, until k equals it upper limit (j in this case).Note that here we have three nested DO loops, and the texthas been indented for easy identification of each associatedEND DO command.

IF ( ) THEN..

ELSE..END IF

IF the logical argument in brackets is satisfied, THEN ex-ecute the following lines of code down to the ELSE com-mand. If the logical argument is not satisfied then executethe commands between ELSE and END IF. Multiple argu-ments using .OR., .AND. have obvious meaning. Note thatthe IF block does not have to contain an ELSE portion. Fur-thermore, if only one command is to be executed the IFstatement can be placed on one line and the THEN com-mand omitted as is used here on the second IF statement.

Notice that in the program layout we have indented sections of DO loops and IF-THEN-ELSEblocks. This helps to clarify the structure of a program.

If you fully understand what you have read, you may now attempt exercise 3 below.

Page 33: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 33 of 91

Go Back

Full Screen

Close

Quit

1.7. Numerical Accuracy

Integer arithmetic can be done with absolute precision but if we want to be able to use very smallor very large numbers then we have to resort to floating point numbers. In Fortran these are calledREAL numbers. Arithmetic involving REAL numbers does not have absolute precision.

The following program explores this problem.

PROGRAM NumericalIMPLICIT NONEREAL :: one, x, y, zINTEGER :: jone = 1.0WRITE (*, *) ’ x (1+x)-1 ’x = oneDO j = 1 , 10

x = x/10.0y = one + xz = y - one ! z should be equal to xWRITE (*, *) x, z

END DOSTOPEND PROGRAM Numerical

Now attempt exercises 4 and 5.

Page 34: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 34 of 91

Go Back

Full Screen

Close

Quit

1.8. Exercises

1. [4 Marks](a) Obtain a copy of the program Triangle.f95 from the departmental web server.

Start theSalford software by double-clicking on thePlato icon, and openthe Triangle.f95 program using the second-from-top-left tool-button. Pressthe F9 key to compile the program; if any mistakes exist in the programthe compiler will report the errors to you. If the compilation produces noerrors, click on the ‘OK’ box and then press Alt-F9 to build the executable.Execute this program by clicking on the ‘run’ box. A window will appear asthe program runs. Enter the three side lengths (use simple numbers to startwith, say 3,4,5) and record the value calculated by the program. Check thisresult analytically. Test the program by entering at least two other (non-right-angled) triangles for which you can determine the area.Remember to keep a record of your work in your logbooks.

(b) The area of the triangle is of course the same regardless of the order in whichyou enter the three lengths; Area(3,4,5)=Area(4,5,3) etc. Save the programunder a different name using the ‘Save As’ option under ‘File’, and modifyit to calculate the area of the triangle using all possible combinations of theordering of the lengths. Do this by calling the function TriangleArea severaltimes with the arguments in different orders eg TriangleArea(a, b, c) andTriangleArea(b, a, c)Remember to place a printout of your modified program in your logbook,explaining the lines of code that you have written. Comment on the results ofyour program.

2. [3 Marks](a) Compile and run the program Round.f95 and confirm that it is works cor-

rectly.

Page 35: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 35 of 91

Go Back

Full Screen

Close

Quit

(b) Make a copy of Round.f95 (Round2.f95, say) and modify it so that the pro-gram calculates the volume of a sphere as well as the area of the circle withthe given radius. You should do this by creating a new procedure, FUNC-TION Volume(radius). Take care to incorporate all the necessary commands;any omissions will be identified by the compiler.One final word of caution; FORTRAN 95 deals with integers precisely, andso division of integers results in rounding down to the nearest integer. Thus4/3 will result in 1 and3/4 will result in 0! However if either of the numbersare real then a real number results: 4.0 / 3 = 4 / 3.0 = 4.0 / 3.0. This situationholds for integer variables as well.

(c) Remember to place a printout of your modified program in your logbook.Explain the purpose of each line in this code. Record some sample outputproduced by the program and comment on how the program works.

3. [4 Marks](a) Compile and run the program Permutations.f95, and record the output in your

logbook. Explain in your own words how the nested do-loops produce theoutput, and how the logical IF commands operate in this application.

Page 36: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 36 of 91

Go Back

Full Screen

Close

Quit

(b) Now return to your version of Triangle.f95 and modify it in the followingways:First change the input lengths to integers but still allow the FUNCTION Tri-angleArea to operate correctly.Second ensure that each input length is a non-negative number (a length can-not be neagative !)Third create a new function that determines whether a triangleexistswiththe three specified lengths and if so whether it isequilateral, isoscelesorscalene. This could be done by creating an integer function which returnsa different integer for each of the above categories. This requires the samelogical constructs used in the Permutations.f95 program.Remember to place a printout of your program in your logbook and to explainthe purpose of each line of code that you have written. Record some sampleoutput produced by the program and comment on whether the program workscorrectly.

4. [ 3 marks]Input the programnumericalusing the editor; save this asnumerical.f95; andrun it.Comment on the results you obtain.In order to understand what is happening, do the calculations by hand. Sim-plify the process by taking only 4 digits for each number.

5. [3 Marks]Write a program which allows the user to enter an integern (0 < n < 100)and then calculates n! the factorial of this integer. To perform this exercisecreate afunction procedureand use do-loops.

Page 37: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 37 of 91

Go Back

Full Screen

Close

Quit

Remember that you must finish your work on this chapter by writing a summary in your logbook.This should summarize in less than 300 words what you have learnt and whether the objectives ofthis chapter have been met.

Page 38: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 38 of 91

Go Back

Full Screen

Close

Quit

Chapter 2

INTRODUCTION TO FORTRAN 95, PART II

Version date: Monday, 19 May 19, 2003

Page 39: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 39 of 91

Go Back

Full Screen

Close

Quit

2.1. Objectives

To introduce additional elements of FORTRAN 95 that are frequently used in this unit, specificallyarrays, array operations and subroutines; and some useful mathematical operations. In additionsome of the graphics facilities provided by theSalfordcompiler software are introduced. On com-pletion of this chapter students will possess the programming knowledge required in the remainderof the unit.

Page 40: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 40 of 91

Go Back

Full Screen

Close

Quit

2.2. Deadline

12 noon Wednesday, 21 May 2003.

Page 41: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 41 of 91

Go Back

Full Screen

Close

Quit

2.3. Arrays

An array is a set of data, all of the same type, arranged in a rectangular block of one or moredimensions. Arrays can be specified in the type declaration at the start of a program block. Forexample

INTEGER :: iamanarray(4,3)REAL :: soami(7)

declares an array called “iamanarray” which hasrank 2 (two dimensions), shape (/4,3/), and size12 (it has 12=4×3 elements). The one dimensional real array “soami” is also declared.

2.3.1. Arrays and Sorting

One of the advantages FORTRAN95/90 enjoys over its predecessors (FORTRAN77, FORTRAN66)is that dynamic arrays are allowed, which means that the size of the array does not have to be spec-ified before the program is compiled but can instead beallocatedduring the program’s execution.The following example uses this facility and introduces the important concept ofsorting. That is,putting a set of data in prescribed order. This program takes a set of integers and orders them.The particular method used in the program is called thebubble sort. This is not the most efficientmethod of sorting but is very easy to understand.

PROGRAM Sort_numbersIMPLICIT NONEINTEGER, ALLOCATABLE :: IntegerArray(:)INTEGER :: number_to_be_sorted, n

Page 42: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 42 of 91

Go Back

Full Screen

Close

Quit

DOWRITE(*,*) ’How many integers will be sorted (READ(*,*) number_to_be_sortedIF (number_to_be_sorted .LE. 12) EXIT

END DO

ALLOCATE (IntegerArray(1:number_to_be_sorted)) ! This allocates the storage! space for IntegerArray

DO n=1,number_to_be_sortedWRITE(*,*) ’Enter integer ’,n,’ : ’READ (*,*) IntegerArray(n)

END DO

CALL Sort(IntegerArray)WRITE(*,*) ’The sorted list of integers is:’DO n=1,number_to_be_sorted

WRITE(*,*) ’Number index ’,n,’ : ’,IntegerArray(n)END DOWRITE(*,*) ’Press ENTER to finish ’READ(*,*)

DEALLOCATE(IntegerArray) ! This releases the space

STOP

CONTAINS

SUBROUTINE Sort(iarray)IMPLICIT NONEINTEGER, INTENT(IN OUT) :: iarray(:)INTEGER :: sort_number, n, m, temp

Page 43: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 43 of 91

Go Back

Full Screen

Close

Quit

sort_number = SIZE(iarray,1) ! The array size can be extracted! the array itself

DO n=1, sort_number-1DO m=n+1, sort_number

IF(iarray(n) .GT. iarray(m)) THENtemp = iarray(n)iarray(n) = iarray(m)iarray(m) = temp

END IFEND DO

END DORETURN

END SUBROUTINE Sort

END PROGRAM Sort_numbers

The new commands that we have not encountered before are:

INTEGER, ALLOCATABLE The appended list of arrays are dynamic, and theirshapes can be determined as required during the pro-gram’s execution. However the dimensions of the ar-rays do need to be specified. Here IntegerArray(:) isa one dimensional array, whereas IntegerArray2(:,:)would be two dimensional. Arrays of up to 7 dimen-sions are allowed.

Page 44: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 44 of 91

Go Back

Full Screen

Close

Quit

ALLOCATE(IntegerArray(1:total))

At this point in the program’s execution, the ar-ray shape is declared by the ALLOCATE com-mand. The one dimensional integer array “Inte-gerArray” has elements IntegerArray(1), IntegerAr-ray(2). . . IntegerArray(total). Note how the lowerbound, 1 in this case, is declared. This lower boundcould have any integer value and, in particular, couldbe negative.

CALL Sort(IntegerArray) This command tells the program to execute the SUB-ROUTINE called “Sort(IntegerArray)” at this stage ofthe program. This subroutine is “contained” in theprogram after the main program unit, in the same waythat FUNCTION procedures would be.

DEALLOCATE(IntegerArray) This releases the memory allocated above to the array“IntegerArray”, which would have to be re-allocatedbefore it could be used again later in the program.

SUBROUTINE This is a type of procedure, which is similar to aFUNCTION except the subroutine name “Sort” is notitself a variable whose value is assigned in the proce-dure.

SIZE(IntegerArray,1) This command gives the size bound of the stated di-mension (in this case IntegerArrayber 1) of the givenarray (IntegerArray). This facility is useful, becauseotherwise the shape parameters of all arrays in a pro-cedure’s argument list would themselves have to beincluded in the list.

Page 45: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 45 of 91

Go Back

Full Screen

Close

Quit

! Comments appear after “!”, which means that thecompiler does not try to interpret anything written onthe same line following this symbol. It is commonpractice to insert comments in programs to indicate toother users how the program works.

IntegerArray(n) Notice how the elements of the array are addressed;IntegerArray(n) is the nth element of IntegerArray.

2.3.2. Defined Types and More Sorting

Now I am now going to consider sorting more complicated objects. First I need tocreatea morecomplicated object. Fortran 95 has a few ’built-in’ types: INTEGER, REAL, COMPLEX, CHAR-ACTER and LOGICAL. You have not used all these yet but you will.

In addition Fortran 95 allows you to create your own types. This can be done as follows:

.

.TYPE Vector

REAL :: x, y, zEND TYPE Vector.Type (Vector) :: MyVector, ArrayOfVectors(25)

MyVector%x = 1.2MyVector%y = 2.6MyVector%z = 0.0

ArrayOfVectors(6)%x = 7.3

Page 46: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 46 of 91

Go Back

Full Screen

Close

Quit

ArrayOfVectors(6)%y = 1.9ArrayOfVectors(6)%z = 2.5..

The first few lines defines thedefined type vector. This has three components: x, y and z. Thenext line declares MyVector to be of typevectorand ArrayOfVectors to be an array of typevectorwith 25 elements. Notice that ’vector’ is a name that I have chosen for the new type: I could havechosen any name. The segments of code show how to use these new variables. You are now goingto modify the integer sorting program so that it reads in a set of vectors and orders them accordingto the magnitudes of the vectors.

If you understand what you have read, you may now attempt the first exercise given at the end ofthis chapter.

Page 47: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 47 of 91

Go Back

Full Screen

Close

Quit

2.4. Whole array expressions

In computational physics we very often deal with matrices. FORTRAN 95 contains useful featuresthat allow operations to be performed on all the elements of an array in parallel. Some examplesare given in the following simple program. The feature RESHAPE which is used in this programneeds some explanation.

The statement

avec = (/1,2,3,4,5,6,7,8,9/)

introduces data into the one dimensional arrayavec. The statement

amat = RESHAPE(avec,(/3,3/))

reshapes this data into a 3-by 3 array. We can think of avec as a column vector

avec =

123456789

amat can be thought of as a square matrix.

Page 48: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 48 of 91

Go Back

Full Screen

Close

Quit

amat =

1 4 72 5 83 6 9

.

Notice that the reshaping is done column-by-column.

You will use the program Wholearrays to study the properties of arrays and of array operations.

PROGRAM Whole_arrays

! Version Date: 19 April 2002

IMPLICIT NONEINTEGER :: avec(6), bvec(6), cvec(6)INTEGER :: amat(2, 3), bmat(3, 2), cmat(2, 3), dmat(2, 2), &

emat(3, 3)INTEGER :: j, k

avec=(/1,2,3,4,5,6/) ! A way of entering a 1D arrayamat = RESHAPE(avec,(/2,3/)) ! This reshapes the elements of avec

! into a 2X3 array amatbvec=(/2,3,4,5,6,1/)bmat = RESHAPE(bvec,(/3,2/)) ! This reshapes the elements of bvec

! into a 3X2 array amat

cvec=(/3,4,5,6,1,2/)cmat = RESHAPE(cvec,(/2,3/)) ! This reshapes the elements of cvec

! into a 2X3 array amat

WRITE(*, *) ’ Matrix a ’

Page 49: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 49 of 91

Go Back

Full Screen

Close

Quit

WRITE(*, ’(3i5)’) ((amat(j,k), k=1,3), j=1,2)

WRITE(*, *) ’ ’WRITE(*, *) ’ Matrix a in detail ’WRITE(*, *) ’ row’, ’ column’, ’ matrix element’WRITE(*, ’(3i5)’) ((j, k, amat(j,k), k=1,3), j=1,2)

! The above prints j, k, amat(j,k) on a single line so that! you can identify the elements of the matrix and! check the way reshape works.! the ’(3i5)’ means put three integers on a line allowing 5 spaces for! each integer

! This is what the matrix looks like if it printed in an unformatted wayWRITE(*, *) ’ ’WRITE(*, *) ’ Matrix a (unformatted)= ’WRITE(*, *) amat

WRITE (*, *) ’ ’WRITE (*, *) ’ Press return to continue’READ (*, *)

WRITE(*, *) ’ ’WRITE(*, *) ’ Matrix b = ’WRITE(*, ’(2i5)’) ((bmat(j,k), k=1,2), j=1,3)

WRITE(*, *) ’ ’WRITE(*, *) ’ Matrix c = ’WRITE(*, ’(3i5)’) ((cmat(j,k), k=1,3), j=1,2)

! Now investigation matrix additionWRITE(*, *) ’ ’

Page 50: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 50 of 91

Go Back

Full Screen

Close

Quit

WRITE(*, *) ’ The sum amat + cmat = ’cmat = amat + cmat ! This adds amat & cmat and put the sum into cmat

WRITE(*, ’(3i5)’) ((cmat(j,k), k=1,3), j=1,2)

! Now investigate element-by-element multiplication (remember that! cmat has changed)WRITE(*, *) ’ ’WRITE(*, *) ’ The element-by-element product amat*cmat = ’cmat = amat*cmat ! This muliplies each element of amat by the

! corresponding element of cmat and puts the! result into cmat

WRITE(*, ’(3i5)’) ((cmat(j,k), k=1,3), j=1,2)

! Note that this is not the same as matrix multiplication

! Matrix multiplication can be done using the built-in function MATMUL

dmat = MATMUL(amat, bmat)emat = MATMUL(bmat, amat)

! Insert code to output these product matrices

WRITE (*, *) ’ Press RETURN to continue ’READ(*,*)STOP

END PROGRAM Whole_arrays

If you understand what you have read, you may now attempt the second exercise given at the end ofthis chapter.

Page 51: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 51 of 91

Go Back

Full Screen

Close

Quit

2.5. Computational Techniques

I have already introduced at one useful technique: sorting. Now I introduce a few more.

2.5.1. Summations

Suppose I need to find the sum of a (possibly large) number of quantities. First I need a variableto hold the summation: I call thisTotal. Then I add the contributions toTotal one by one. Thiscould be done as follows:

.

.Total = 0.0DO j = 1, n

Total = Total + ...END DO..

where. . . contains the formula for calculating the j th element of the summation.

If the quantities to be summed have been put into anarray then Fortran 95 has a built-in mechanismfor summation:

.

.Total1 = SUM(S(1:n))Total2 = SUM(T(n1:n2))

Page 52: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 52 of 91

Go Back

Full Screen

Close

Quit

Total3 = SUM(U(n1:n2, n3)).

In this caseTotal1 is the sum of the elements1, . . . , n of one dimensional array S;Total2 is thesum of the elementsn1, . . . , n2 of one dimensional array T; andTotal3 is the sum of the elementsn1, . . . , n2 of then3th column of two dimensional array U.

2.5.2. Integration

Suppose now that I need to evaluate the integral∫ b

a

f (x)

In general I can approximate an integral by means of the trapezoidal rule. The essence of this is asfollows:

The range of the integral is divided intoN equal intervals of sizeδx (= (b − a)/N) and thefunction is evaluated at co-ordinates

xj = a + jδx j = 0, . . . , N

Between these co-ordinates the function (integrand) is approximated by a sequence of straight-linesegments.

The result for the integral is

(b− a)N

12

(f (x0) + f (xN )) +N−1∑j=1

f (xj)

Page 53: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 53 of 91

Go Back

Full Screen

Close

Quit

2.5.3. Differentiation

Differentiation is used throughout physics. In order to evaluate a derivative numerically, I make useof the definition:

df (x)dx

= limδx→0

f (x + δx)− f (x− δx)2 δx

The approximationto this suitable for computation is obtained by takingδx to besmall but notzero. Generally the approximation gets better asδx gets smaller but you should always be aware ofthe limitations of computers. (Remember the program numerical.f95!)

Now attempt exercise 3.

Page 54: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 54 of 91

Go Back

Full Screen

Close

Quit

2.6. Graphics

There are no standard graphics facilities available in FORTRAN 95. Instead each compiler maycome with its own graphics routines. The following subroutine, which is used in the programStline.f95, makes use of theSalford software’s graphics. The subroutine plots the data pointsx(n), y(n) as circles and draw the least-squares-fit line for the points which has gradient s andintercept c. With the comments the graphics commands may be self-explanatory! The main ele-ment of the graphics is the drawing subroutine:

CALL draw_line@(x1, y1, x2, y2, RGB@(200, 0, 0))

This draws a line from(x1, y1) to (x2, y2) in a colour specified by its Red, Green & Blue intensities.(0, 0, 0)=black,(255, 255, 255)=white,(255, 0, 0)=red, etc.

The co-ordinates are integer variables and are in pixels. (0, 0) is the top left of the window.

Read the comments associated with the program carefully.

SUBROUTINE plotgraph(x, y, s, c, deltas, rotated)

USE MSWINIMPLICIT NONEREAL (KIND=P), INTENT(IN) :: x(:), y(:), s, c, deltasLOGICAL, INTENT(IN) :: rotatedINTEGER :: n, j, intg, handle1, ctrl1REAL (KIND=P), ALLOCATABLE :: cx(:), cy(:)REAL (KIND=P) :: xmin, xmax, ymin, ymax, xavg, yavgREAL (KIND=P) :: ystart, yendREAL (KIND=P) :: gscaleREAL (KIND=P) :: ninetydegrees=90.0P

Page 55: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 55 of 91

Go Back

Full Screen

Close

Quit

INTEGER (KIND=3) :: fullscreenheight,fullscreenwidth, &graphics_width, graphics_height

INTEGER (KIND=3) :: graphics_top, graphics_bottom, &graphics_left, graphics_right, &graphics_x, graphics_y

CHARACTER (LEN=20) :: string

n = SIZE(x, 1) ! n is the size of the array x

! Allocate space for arrays cx, cy which are copies of x & yALLOCATE (cx(1:n), cy(1:n))

IF (rotated) THENcx = REAL(y, KIND(1.0))cy = REAL(x, KIND(1.0))

ELSEcx = REAL(x, KIND(1.0))cy = REAL(y, KIND(1.0))

END IF

! Find the minimum and maximum values of cx & cyxmin = MINVAL(cx(:))xmax = MAXVAL(cx(:))ymin = MINVAL(cy(:))ymax = MAXVAL(cy(:))

! Open Window with 2 panels

intg = winio@(’%ca[Computational Physics---StLine]&’)intg = winio@(’%1.2ob[panelled]&’) ! 1.2 means 1-by-2

Page 56: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 56 of 91

Go Back

Full Screen

Close

Quit

! Find screen resolutionfullscreenwidth = Clearwininfo@(’ScreenWidth’)fullscreenheight = Clearwininfo@(’ScreenDepth’)

WRITE (*, *) fullscreenwidth,fullscreenheight

! Choose a window size which a fraction of full screen

gscale = 0.6

graphics_height = INT(fullscreenheight*gscale)

graphics_width = INT(fullscreenwidth*gscale)

! Put graphics window in top panel

! Set handle for window --- only really necessary if more than one! graphics window is usedhandle1 = 999 ! Arbitrary integer but different from other

! window ‘handles’

intg = winio@(’%‘gr[white, rgbcolours] %cb&’,graphicswidth, &graphics_height, handle1)

intg = winio@(’%ww%lw&’, ctrl1)

! Put title in bottom panelintg = winio@(’%18bt[Straight Line Fit] %cb’)

! Set limits of plotting framegraphics_top = INT(0.1*graphics_height)graphics_bottom = INT(0.8*graphics_height)graphics_left = INT(0.2*graphics_width)

Page 57: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 57 of 91

Go Back

Full Screen

Close

Quit

graphics_right = INT(0.9*graphics_width)

! Plot points

intg = select_graphics_object@(handle1)

! Start copying graphics to metafileintg = open_metafile@(handle1)

DO j = 1, ngraphics_x = INT((cx(j)*(graphics_right-graphics_left) + &

(graphics_left*xmax-graphics_right*xmin))/ &(xmax-xmin))

graphics_y = INT((cy(j)*(graphicstop-graphics_bottom) + &(graphics_bottom*ymax-graphicstop*ymin))/ &(ymax-ymin))

CALL fill_ellipse@(graphics_x, graphics_y, 2, 2, RGB@(100,0, 200))END DO

! Draw axesCALL draw_line@(graphics_left, graphics_bottom,graphics_right, &

graphics_bottom, RGB@(0,0,0))CALL draw_line@(graphics_left, graphics_bottom,graphics_left, &

graphics_top, RGB@(0,0,0))CALL draw_line@(graphics_left, graphics_top,graphics_right, &

graphics_top, RGB@(0,0,0))CALL draw_line@(graphics_right, graphics_bottom,graphics_right, &

graphics_top, RGB@(0,0,0))

! Draw straight-line fitystart = s*xmin + cyend = s*xmax + c

Page 58: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 58 of 91

Go Back

Full Screen

Close

Quit

CALL draw_line@(graphics_left, &INT((ystart*(graphicstop-graphics_bottom) + &(graphics_bottom*ymax-graphicstop*ymin))/ &(ymax-ymin)), graphics_right, &INT((yend*(graphic_stop-graphics_bottom) + &(graphics_bottom*ymax-graphicstop*ymin))/ &(ymax-ymin)), RGB@(0,0,0))

! Draw straight-lines with uncertainties here

! Write labels for axes

string = ‘ x-axis’CALL rotatefont@(0.02)CALL drawtext@(string, graphics_left+30,graphics_bottom+20,RGB@(0,0,0))

string = ‘ y-axis’CALL rotatefont@(ninetydegrees)CALL drawtext@(string, graphics_left,graphics_bottom,RGB@(0,0,0))

! Copy metafile to clipboard -- you can then use Word to! capture and print this

! Stop recording the graphicsintg = metafile_to_clipboard@()intg = close_metafile@(handle1)

DEALLOCATE (cx, cy)

RETURN

END SUBROUTINE plot_graph

Page 59: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 59 of 91

Go Back

Full Screen

Close

Quit

If you think you understand the drawing features of this subroutine, proceed to exercise 4.

Page 60: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 60 of 91

Go Back

Full Screen

Close

Quit

2.7. Exercises

1. [4 Marks](a) Compile and execute the Sortnumbers.f95 program, and check that it works

properly. In order to understand how it works take a set of four integers (5 13 2) and perform the operations of thesort subroutine manually.Remember to keep a record of your work in your logbooks.

(b) Make a copy of the program, and modify it as follows: Change the relevantvariables fromINTEGERto TYPE (vector). The criterion for sorting involvesthe magnitudes of the vectors: The magnitude of vectorA is SQRT (A%x ∗∗2+A%y∗∗2+A%z∗∗2). Allow the user to enter a set(totalnumber < 12)of vectors, and then order these in terms of their magnitudes.

2. [4 Marks](a) Compile and execute the Wholearrays.f95 program and verify that the

element-by-element addition and multiplication have worked correctly.(b) Use the command MATMUL(amat, bmat) to multiply the matrices amat and

bmat. Consult theSalford FTN95 Help (Language Overview - Arrays)onusing this command. Verify by hand that the command works correctly.

(c) Similarly find out how the following commands work, implement them inyour program and verify that they produce the correct results:DOT PRODUCT, MAXLOC, MAXVAL, TRANSPOSE, RESHAPE,LBOUND, UBOUND.

3. [5 Marks](a) Use the two methods in theSummationssection to to calculate the sum of1n2

from n = 5 to n = 1000(b) Use thetrapezoidaltechnique to integratesin(x) from x = 1 to x = 10

Page 61: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 61 of 91

Go Back

Full Screen

Close

Quit

(c) Use the formula in theDifferention section to calculate the derivative ofsin(x) at x = 1. Explore a range of values forδx and compare the com-puted results with the correct answer. Comment on your results.

4. [4 Marks](a) Compile and execute the Stline.f95 program which utilises the graphics sub-

routine Plotgraph. The program ask the user to enter a set of points to whichit fits the least-square line. Check that the program is working correctly for asmall sample set. Create a schematic flow-chart of how the program works.

(b) The program declares the precision of its variables through the KIND state-ment. Find out about the possible precision for the variable types in theSALFORD FTN95 Help facility and record what you learn.

(c) Obtain a hardcopy of the graph produced by the program in the followingway. The program writes a copy of the graph to the clipboard. Open up aWORD file and paste the graph into it. The graph can now be stretched asappropriate and printed from WORD in the usual way.

(d) Modify the program so that the Plotgraph routine also draws lines showingthe uncertainties in the gradient deltas. The lines should pass through thecentre-of-mass co-ordinates of the data set.

Remember that you must finish your work on this chapter by writing a summary in yourlogbook. This should summarize in less than 300 words what you have learnt and whether theobjectives of this chapter have been met.

Page 62: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 62 of 91

Go Back

Full Screen

Close

Quit

Chapter 3

EQUATIONS OF MOTION IN PHYSICS

Version date: Thursday, 12 June 2003

Page 63: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 63 of 91

Go Back

Full Screen

Close

Quit

3.1. Objectives

On completion of this chapter students will have encountered and applied some common numericalmethods for solving equations of motion which will be used later in the unit. They will also havereviewed the behaviour of simple harmonic oscillators and resonance in forced oscillator systems.

Page 64: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 64 of 91

Go Back

Full Screen

Close

Quit

3.2. Deadline

12 noon Wednesday, 11 June 2003.

Page 65: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 65 of 91

Go Back

Full Screen

Close

Quit

3.3. The Numerical Methods

In dynamics the equations of motion that arise are typically in the form

md2x (t)

dt2= F (3.1)

wherex is a particle co-ordinate which varies with timet; andF is the force acting on the particleof massm. In general this force will be a function ofx, t and the particle’s velocityv. In this casethe problem is to findx as a function of time given the positionx0 and velocitytextbfv0 at someinitial time t0.

However before we can tackle this second-order equation we first investigate the solution of asimpler, first-order equation:

dq

dt= D (3.2)

whereq represents some physical quantity which varies with t andD depends onq and t. The aimhere is to find a numerical method which enable us to determineq at some time t given its valueq0

at some time t0.

We choose to try to evaluateq at a discrete set of equally spaced times

tn = t0 + nτ,

wheren is an integer andτ is the time-step. As an aid to developing a numerical approximation,we first write down an exact relation between neighbouring time steps:

q (tn+1) =∫ tn+1

tn

D (q, t) dt (3.3)

Page 66: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 66 of 91

Go Back

Full Screen

Close

Quit

This is obtained by integrating equation between tn and tn+1. However there is a problem; if wehave evaluatedq(t) one step at a time up to thenth step we donot know q(t) throughout the rangeof the integral in equation (3.3) but only at the initial pointtn.

A crude approximation, calledEuler’s method, involves simply replacingD(q(t),t) in the integralby the constant valueD(q(tn), tn). This gives rise to the approximate result

q (tn+1) = q (tn) + D (q (tn) , tn) τ (3.4)

and this relation can be used to step forward in time, starting from the known valueq(t0) . Howeverthis is not a very good procedure, because over long times the errors tend to accumulate rapidly.

In order to improve on this we need a better way of estimating the integral in equation (3.3). Onemethod of achieving this improvement is known as thepredictor-corrector method. This hasmany variations but the simplest is as follows. Use the Euler method (3.4) to provide a roughestimate ofq(tn+1) (this is called theprediction stage) and I denote its value byq(p)(tn+1). Thenuse this estimate to approximate the mean value of the integrand in equation (3.3) over the range[tn, tn+1] (this is called thecorrection stage). This gives a new, improved estimate ofq(tn+1) :

q (tn+1) = q(p) (tn) +12

[D (q (tn+1) , tn+1)−D (q (tn) , tn)] τ (3.5)

The second term on the right-hand side of equation (3.5)is called thecorrection. In this termq(tn+1)is (initially) replaced by thepredictionq(p)(tn+1). Note that the correction stage can be iterated afew times using the increasingly better estimates in the right-hand side to improve the accuracy ofthe procedure. In other wordsq(tn+1) in the equation keeps getting replaced by the latest estimate.

As a rough guide to the accuracy of these numerical approximations, the error in each step usingequation (3.4) is ≈ τ2

2dDdt whereas using equation (3.5)) the error is≈ τ3

12d2Ddt2 . For small enough

step-sizeτ the predictor-corrector method is greatly superior to the Euler method.

Page 67: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 67 of 91

Go Back

Full Screen

Close

Quit

We now return to the second-order equations that more often arise in Physics. Equation (3.1) can

be written as a pair of first-order equations:

dxdt

= vdvdt

= Fm

(3.6)

If we packagethe left-hand sidesx andv as an arrayq (q(1) = x andq(2) = v) andpackagetheright-hand sidesv andF/m as another arrayD (D(1) = v andD(2) = F/m) then equations (3.6)can be written as the single equation (3.2) providing we interpretq andD as arrays of size two:

dqdt

= D ⇒ d

dt

[xv

]=[

vF/m

](3.7)

The approximation procedures, Euler and Predictor-Corrector, can then be applied directly to thiscase.

This method can be extended to higher-order differential equations, so that (3.2) can in fact be usedto solve an Nth order differential equation. The Euler and Predictor-Corrector methods are suppliedas subroutines in the program ‘diffequ.f95’.

If you think you understand what you have read, you may now attempt exercise 1 at the end of thischapter.

Page 68: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 68 of 91

Go Back

Full Screen

Close

Quit

3.4. The forced damped oscillator

Consider now the example of a harmonic oscillator that is driven by a sinusoidal applied force. Theequation of motion for this system is

md2x

dt2= Focos (ω t)− r

dx

dt− sx (3.8)

where as usualx is the displacement of the oscillator from its equilibrium position at timet, m isthe mass of the oscillator,s is the ‘spring constant’ of the oscillator, andF0 is the amplitude andωthe angular frequency of the driving force. A frictional damping force proportional to the velocityof the oscillator has also been included andr is the constant of proportionality.

Most textbooks analyse this type of system using complex numbers (see for example “The physicsof vibrations and waves” by H.J. Pain). In the steady state, i.e. after the initial transients caused bythe starting conditions have died out, it is predicted that the oscillator will have the displacementand velocity

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

where the amplitude is

A =F0

ω

√r2 + (mω − s/ω)2

(3.10)

and the phase angleφ is the phase angle of the complex number

( s

ω−mω

)+ ir

Page 69: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 69 of 91

Go Back

Full Screen

Close

Quit

Fortran has a built in functionATAN2(y, x) which gives the phase angle of the complex numberx + iy. Using this function, the phase angleφ is given by

φ = ATAN2( s

ω−mω, r

)(3.11)

Theexperimentalamplitude can be calculated using

√x2 +

( v

ω

)2

(3.12)

Theexperimentalphase angle can be calculated using:

φ = ωt + ATAN2( v

ω, x)

(3.13)

Unfortunately this does not necessarily yield an answer in the required range(−π, π) and we usu-ally have to add or subtract multiples of2π.

We could use the following piece of code to add or subtract the appropriate number of2πs.

DOIF (phase .GT. pi) THEN

phase = phase - twopiELSE

EXITEND IF

END DODO

IF (phase .LT. -pi) THENphase = phase + twopi

Page 70: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 70 of 91

Go Back

Full Screen

Close

Quit

ELSEEXIT

END IFEND DO

Equation (3.13) can be deduced as follows. According to equation (3.9) if I form the complexnumberx + iv/ω I get

x (t) + iv (t)w

= A exp [−i (ωt− φ)]

and so the phase angle, which can be worked out using

ATAN2( v

ω, x)

= φ− ω t.

Equating these two terms gives (3.13).

The program ‘drosc.f95’ finds the numerical solutions to equation (3.8) using the above predictor-corrector subroutine with the boundary condition that the oscillator starts from rest at its equilibriumposition. The parameters are set to be

F0 = m = s = 1.0, r = 0.5,

although these can easily be changed in the ‘derivs’ subroutine.

If you think you understand what you have read, you may now attempt exercises 2 and 3 below.

Page 71: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 71 of 91

Go Back

Full Screen

Close

Quit

3.5. Exercises

1. [6 Marks](a) Compile and run the program ‘diffequ.f95’, and make sure you un-

derstand how it works. It is set up to find the solution to the simpleharmonic oscillator equation of motion. Choose a suitable final time(sayt = 10) and a reasonably small step size, say0.025. Recall thatthe angular frequency of the harmonic oscillator isω =

√s/m = 1

in this program, wheres is the spring constant andm the mass of theoscillator. What happens if you make the step size too large?

(b) Use this program to test the Euler approximation for solving second-order differential equations. The program is set up to solve the har-monic oscillator equation so that we know theexactsolution. Theprogram uses this known exact solution to determine the relative rmserror in the calculated solution. How small must you make the step-size for the Euler method to work reasonably well, say with a relativerms error of order10−3?

(c) Now repeat the exercise using the Predictor-Corrector procedure.First with one iteration of the correction stage then two. In compar-ing the numerical methods you should compare the accuracy whichresults from the same (or nearly the same) numerical effort. In orderto make sensible comparisons, a step-sizedt for the Euler methodshould be compared with a step-size2.dt for the predictor-correctorwith one correction stage and3.dt for the predictor-corrector withtwo correction stages.

Page 72: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 72 of 91

Go Back

Full Screen

Close

Quit

(d) Comment on the results of your work, paying particular attentionto whether or not it is worthwhile implementing the more elaboratePredictor-Corrector method in solving differential equations; and, ifso, whether it worth using two iterations rather than one.

(e) Remember to keep an accurate record of your work in your log-book.

2. [5 Marks](a) Run the program ‘drosc.f95’ using different values of the driving

frequency ‘ω’. Make sure you understand how the program works,and comment on the results.

(b) Investigate how, in steady state, the amplitude and phase of the os-cillation, depend on the driving frequency. To do this you need tomonitor the expressions for theexperimentalamplitude and phase(including the removal of the appropriate number of2πs). Explainyour method in detail and record your results.

(c) Use the program ‘stline.f95’ to test whether your numerical re-sults agree with the predictions of the theory. To do this de-termine the steady-stateexperimentalamplitude and phase fora few frequencies. Then use STLINE to plot these valuesagainst the corresponding theoretical predictions. That is, plotAmplitude(experiment) against Amplitude(theoretical) andphase(experimental) againstphase(theoretical). If the theoryand experiment agree you should, in each case, get a straight linewith slope one.

[5 Marks]

Page 73: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 73 of 91

Go Back

Full Screen

Close

Quit

3. [6 Marks]Modify your ‘drosc.f95’ program to produce plots of the (steady state) dis-placement amplitude and phase difference as a function of frequency. In-vestigate the effects of varying the damping coefficient ‘r’ on your results.This can be done by enclosing time stepping DO LOOP inside anotherwhich steps through various omegas; and creating some new variables tohold the data points to be plotted.

Remember that you must finish your work on this chapter by writing a summary in yourlogbook. This should summarize in less than 300 words what you have learnt and whether theobjectives of this chapter have been met.

Page 74: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 74 of 91

Go Back

Full Screen

Close

Quit

Chapter 4

PLANETARY MOTION

Version date: Thursday, 12 June 2003

Page 75: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 75 of 91

Go Back

Full Screen

Close

Quit

4.1. Objectives

In this section you will investigate the motion of planets in the solar system.

On completion of this chapter you will have gained experience in applying numerical methods forsolving equations of motion of planets and have explored the nature of the orbits; and you shouldunderstand the significance of the conservation of angular momentum.

You should also have gained experience in using the editor (to re-use code from other programmes);and in manipulating data in files.

Page 76: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 76 of 91

Go Back

Full Screen

Close

Quit

4.2. Deadline

12 noon Wednesday, 2 July 2003.

Page 77: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 77 of 91

Go Back

Full Screen

Close

Quit

4.3. Equations of Motion.

We will take a simplified view of the solar system in which we assume the mass of the Sun is somuch larger than that of any planet that we can neglect the effects of the planets on each other andcan neglect the motion of the Sun.

The mass of the largest planet is about one thousandth of the mass of the Sun and so, in general,this approximation should be accurate to about one part in one thousand. However in “our neigh-bourhood” the planets are smaller and the approximation is better than this.

In this approximation the force on a given planet is only due to the Sun and so Newton’s equationfor the motion of the planet is

md2rdt2

= −GmMSrr3

(4.1)

wherer is the position vector of the planet,r is its magnitude, G is the gravitational constant andMS is the mass of the Sun which is at the origin of the co-ordinate system.

Page 78: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 78 of 91

Go Back

Full Screen

Close

Quit

4.4. Conservation of Angular Momentum

We first show that the angular momentum of the planet is conserved and look at the consequencesof this.

It is useful to define the vectorh,

h = r ∧ drdt

(4.2)

wheredrdt is the velocity vector.h is theangular momentum per unit mass.

The derivative ofh is:

dhdt

=(r ∧ d2r

dt2

)+(

drdt∧ dr

dt

)(4.3)

The second term on the right-hand side vanishes becauseb∧b is zero for any vectorb. In the firstterm we can use (4.1) to substitute for the second derivative.

This gives

dhdt

= −GMS

r3(r ∧ r) = 0 (4.4)

Hence the vector h is constant. (i.e. does not change over time). From the definition (4.2) r andv are both perpendicular to this constant vectorh. This means that the planet moves in the planewhich is perpendicular toh and which contains the Sun.

This is important because it means that the motion is essentiallytwo-dimensional.

Now attempt Exercise 1 at the end of the chapter

Page 79: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 79 of 91

Go Back

Full Screen

Close

Quit

4.5. Polar Co-ordinates

Since the motion is in a plane we can specify the planet by means of polar co-ordinatesr andϕwhere r is the distance from the sun andϕ is the angle relative to some axis in the plane. I shallchooseϕ so that it is zero at the, so-called, aphelion. This is the maximum distance of the planetfrom the Sun.

In terms of these co-ordinates the component of acceleration along the radius isr − rϕ2 and thecomponent perpendicular to the radius vector isrϕ + 2rϕ

Hence Newton’s equation (4.1) becomes in these co-ordinates the following pair of equations ofmotion:

d2rdt2 = r dϕ

dt

2− GMS

r2

d2ϕdt2 = − 2

rdrdt

dϕdt

(4.5)

Page 80: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 80 of 91

Go Back

Full Screen

Close

Quit

4.6. Numerical solution of equations of motion

We will next set about solving these equations of motion. That is, we suppose that the co-ordinates(r,ϕ) and the velocities(r, ϕ)are known at some initial time and we want to determine the co-ordinates at succeeding times.

We are going to use the methods introduced in chapter 3. Each of the second-order equations (4.5)can be converted into two first-order equations. In order to achieve this we introduce two newvariablesv – the radial velocity – andω – the angular velocity. The four first-order equations arethen

drdt = v

dvdt = rω2 − GMS

r2dϕdt = ω

dωdt = − 2

rdrdt

dϕdt

(4.6)

We can express these equations in the condensed form

dq

dt= D (4.7)

whereq andD are column vectors with elements:

q =

rvϕω

(4.8)

D =

v

rω2 − GMS

r2

ω− 2

r vω

(4.9)

Page 81: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 81 of 91

Go Back

Full Screen

Close

Quit

4.7. Energy and Angular Momentum

With a little more effort we could have done some integration on equations (4.5) to obtain the twoconserved quantities:

h = r2ωE = 1

2

(v2 + r2ω2

)− GMS

r

(4.10)

The first of these is the angular momentum (per unit mass) introduced above and the second is theenergy per unit mass.

If we evaluate the right-hand sides of these expressions for h and E at each step in the numericalprocedure then we have a measure of the accuracy of the procedure. In the numerical procedure hand E will not be precisely constant: The relative variation in the calculated values compared to saythe initial values gives us an estimate of relative accuracy of the overall calculation.

Page 82: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 82 of 91

Go Back

Full Screen

Close

Quit

4.8. Units

We choose units as follows:

unit of time = 1 day

unit of distance = 109m.

In these units the constant GMS is

GMS = 990.6898

Page 83: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 83 of 91

Go Back

Full Screen

Close

Quit

4.9. Initial Values

At some initial time there are four parameters which define the future orbit:

the initial radius and radial velocity r0, v0; and

the initial angle and angular velocityϕ0 andω0.

In principle these can be chosen arbitrarily. However you should realise that not every choice willyield a bound orbit. In an unbound orbit the planet escapes from the solar system. A bound orbitarises only when the energy of the planet, equation (4.10), is negative. That is for a bound orbit weneed to choose r0, v0, andω0 such that

(v20 + r2

0w20

)<

2GMS

r0.

Below are some choices of initial data for Mercury, Venus and Earth. In each case the choicecorresponds to the maximum distance (aphelion) of the planet from the Sun. When the radialdistance is a maximum the radial velocity must be zero.

Mercury

r0=69.81802 ,ϕ0 = 0

v0= 0,ω0= 0.0480869.

This implies initial (and hopefully constant) values for h and E of :

Page 84: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 84 of 91

Go Back

Full Screen

Close

Quit

h0= 234.402

E0 = −8.55382

Venus

r0=108.938 ,ϕ0 = 0

v0= 0,ω0= 0.0275888

The initial values for h and E are :

h0= 327.410

E0 = −4.57763

Earth

r0=152.0997 ,ϕ0 = 0

v0= 0,ω0= 0.0166386.

The initial h and E are :

h0= 384.924

Page 85: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 85 of 91

Go Back

Full Screen

Close

Quit

E0 = −3.31112

Comet Encke

r0=1782.2 ,ϕ0 = 0

v0= 0,ω0= 0.0001636.

The initial h and E are :

h0= 519.6

E0 = −0.5134

Page 86: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 86 of 91

Go Back

Full Screen

Close

Quit

4.10. The Programme

An initial version of the programme is PLANETS.F95 and is on the Physics Intranet page. Youwill need to modify the programme so, after downloading the original, make a copy with a differentname such as PLANETS1.F95.

The planets program makes use of REAL KINDS. So before you get to grips with the program wewill investigate these. FORTRAN95 give the programmer some flexibility in the choice of REALvariables. Suppose we decide we want to use real variables in the form

A× 10B

where A has at least 10 significant figures and the range of B includes−100 to +100. Then in theprogram we would declare an integer parameter

INTEGER, PARAMETER :: P=selectedreal kind(10, 100)

If the compiler can achieve what we want, P is returned as a positive integer that identifies theappropriate REAL KIND. Note that P itself is an integer that is used to label the particular realkind: it is NOT a real variable.

We can then use this integer parameter P to define REAL variables with the desired (or better)precision:

REAL (KIND=P) :: a, b, c

We can also use constants in the program to this precision as follows:

1.0 P, ,2.5P

Page 87: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 87 of 91

Go Back

Full Screen

Close

Quit

Notice that if we simply use 1.0 or 2.5 then these will only have the precision of the basic REALKIND (usually 6 digit accuracy).

If the compiler cannot achieve the desired accuracy then P is returned with a negative value and anyattempt to use it to define a REAL KIND will produce an error.

Now attempt Exercises 2 & 3 at the end of the chapter

Page 88: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 88 of 91

Go Back

Full Screen

Close

Quit

4.11. Kepler’s Laws

Kepler (1571-1630) discovered his three laws of planetary motion by observation (of Brahe’s data)before Newton’s theory of gravitation. His first and second laws were published in 1609 and histhird in 1619.

First Law: Keplar’s first law states that the orbit of a planet is an ellipse with the Sun at onefocus.

How can we check whether our computed orbit is an ellipse ?

The equation of an ellipse, in the polar co-ordinates we are using, is

r =R

1− εcos (ϕ)(4.11)

where R andε are constants defined by

R =h2

GMS(4.12)

ε =

√√√√(1 +2Eh2

(GMS)2

)(4.13)

ε is called theeccentricity. ε=0 corresponds to a circular orbit: the largerε the more elongated theorbit.

If we plot y=r versus x=R/(1 -εcos(ϕ)) then, if the orbit really is an ellipse, we should obtain astraight with slope 1 and abscissa 0.

Second Law: The radius vector sweeps through equal areas in equal times.

Page 89: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 89 of 91

Go Back

Full Screen

Close

Quit

If in (small) timeδt the angleϕ changes toϕ + δϕ then the area swept out by the radius vector isr2δϕ . Hence the area swept out per unit time is

r2 δ ϕ

δ t→ r2ϕ

Kepler’s second law implies that this is constant. However you should have already checked this(Exercise 5) under the guise of “conservation of angular momentum”.

Third Law: The square of the period is proportional to the cube of the major axis.

Now attempt Exercise 4

Page 90: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 90 of 91

Go Back

Full Screen

Close

Quit

4.12. EXERCISES

Exercise 1 [3 Marks]

How would the equation of motion of a particular planet change from (4.1) if we were to includeinteractions with other planets ?

The angular momentum of a particular planet will no longer be conserved if we include interactionswith other planets. Explain why and discuss the consequence for the orbit.

Exercise 2 [2 Marks]

Download the program kindtest.f95 and explore the REAL KINDS that are available on the Salfordcompiler.

Exercise 3 [6 Marks]

Now download the planets.f95 program and compile and run the programme.

You will be prompted to choose a particular planet or comet; or to enter your own choice for theinitial values r0, ϕ0 ,v0 andω0. Try the data given for Mercury, Venus, Earth and comet Encke andoutput the data to four separate files.

Record your observations. What is the period? What is the perihelion (minimum distance fromSun) and at what angle does it occur ?

Modify the program planets.f95 so that

h = r2ωE = 1

2

(v2 + r2ω2

)− GMS

r

are evaluated initially and at each subsequent time-step. Output these values to a file.

Page 91: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 91 of 91

Go Back

Full Screen

Close

Quit

Physics says that these two values should be constant. In fact because the approximate calcula-tion they will fluctuate. The magnitude of the fluctuations is an indication of the accuracy of thenumerical procedure.

Use your results to estimate the accuracy of the numerical procedure.

Exercise 4: [6 Marks]

Check that the computed orbits are ellipses in the following way. In the program planets.f95 intro-duce allocatable arrays x, y and variables s, c, deltas, and deltac. Allocate the arrays x and y withsize nsteps after the completion of the calculation of the orbit.

Then use a DO loop to read data into the variables x(j), y(j) from the disc file:

REWIND 15 ! This positions the file at the startDO j=1,n_steps

READ (15, FMT=’(5(2X,E14.6))’) t, q(1), q(2), q(3), q(4)! The above line should be essentially the same as the WRITE line! which stored the data! Notice that we have to read all the data in the record, even the!items we do not wanty(j) = q(1)x(j) = R/(one - epsi*cos(q(3)))

END DOCALL Linfit(x, y, s, c, delta_s, delta_c)

The subroutine Linfit should be extracted from the file Stline.f95 and inserted into the ‘CONTAINS’section of the current programme.

The outputs s and c and their uncertainties deltas and deltac give a measure of the deviation of theorbit from an ellipse.

The above programme segment is only a guide. You should ensure that all the variables you use are

Page 92: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 92 of 91

Go Back

Full Screen

Close

Quit

properly declared and that R and epsi should be given appropriate values

Using the data you have already obtained for Mercury, Venus, Earth & Encke, check the validity ofKepler’s third law. Note: the major axis is the sum of the minimum and maximum distances fromthe Sun

Remember that you must finish your work on this chapter by writing an abstract in yourlogbooks. This abstract should summarize in less than 300 words what you have learnt andwhether the objectives of this chapter have been met.

Page 93: Computational Physics Home PageFortran 90/95 Explained By Michael Metcalf and John Reid Oxford University Press ISBN 0-19-851888-9 $35.00 Fortran 90 for Scientists and Engineers By

Home Page

Title Page

Contents

JJ II

J I

Page 93 of 91

Go Back

Full Screen

Close

Quit