Anda di halaman 1dari 18

Numerrcal Methods for Engineers

A PROGRAMMING APPROACH

t
t
I

I
i
I

Frontispiece (opposite title page). Train crash at Montparnasse Station in 1895. Numerical modelling of
short duration events such as this impact problem could.be tackled using an explicit one-step method to
solve the differential equations ofmotion (seeChapter 7). Full scale physical modelling on the other hand,
can be rather time-consuming and expensive.(Photograph courtesy of Editions Gendre, Paris.)
rr
' t
t

I
Numerical Methodsfor Engineers
A PROGRAMMING APPROACH

D.V. Griffithsand I.M. Smith


Both of the Uniuersity of Manchester

I
I

*
t

OXFORD

BLACKWELL SCIENTIFIC PUBLICATIONS


LONDON EDINBURGH BOSTON

MELBOURNE PARIS BERLIN VIENNA.,

ul
To Valerie, Janet and Catherine

@ l9l by D I S T R IB U T O R S
Blackwcll Scicnti6c Publications
Marston Book Scrviccs Ltd
Editorial offic:
PO Box 87
Osncy Mcad, Oxford OX2 OEL
Oxford OX2 ODT
25 John Strccr. London WCIN 2BL
(Ordrs Tel: 0865 791t55
23 Ainslic Placc, Edinburgh EHI 6AJ
Fax: 0865 791927
3 Cambridgr Ccntcr, Cambridgc
Tclcr:837515)
Massachusctts 02142, USA
54 Univcrsity Strcct, Carlton USA
Victoria 3053, Australia Blackwcll Scicntifrc Publietions. Inc.
3 Cambridgc Crntcr
All rights rcscrucd. No part of this Cambridgc, MA 02142
publietion may bc rcproduccd, storcd (Or da s'lel: 800 759{1 02)
in a rctricval systcm, or transmittcd,
Canada
in any fom or by any mcans,
Oxford Univcnity Prcs
cletronic, mrchanical photmpying
70 Wynford Drivc
rccording or othcruisc without thc
Don Mills
prior pcrmission of thc mpyright
Ontario M3C lJ9
owncr.
(Ordus Tcl: (416) 441-2941\
First publishcd l99l Auslralia
Blackwcll Scicnti6c Publications
Sct by Intcrprint Lrd, Malta (Autralia) Pty Ltd
Printcd and bound in Grcat Britain 54 Univcrsity Str€t
by Hartnolls Ltd, Bodmin Carlton, Victoria 3053
(Ord.as'f cl: (03) 3474100)

British Library
Cataloguing in Publication Data

Griffths D.V. (Dcnwood Vaughan), 1953-


Numcriel mcthods for cngines: a programming
approach.
l. Engiacring. Analysis- Numcriel mcthodd
I. Titlc II. Smitb, I.M. (Ian Moffat), I9{0-
620

ISBN 0{3242751-7
ISBN G63242753-3 pbk

Library of Congrcss
Cataloging in Publication Data

Griffithr D.V.
Numcrical methods for enginccn: a programming
approach/D.V. criffi ths, I.M. Smirh.
p. m.
Includcs bibliographial rcfcrcnccs.
ISBN 0-53242751-7. - ISBN 0-63242753-3 (pbk.)
l. Enginering mathcmatics-Data prmsin&
2 Numcrical analysis-Data proccssing. I. Smith
I.M. II. Title.
T4335.G75 l99l
62(I.001'51*-dc20
1v
!

Contents

List of Programs,ix

Preface,xi
a

xiii
Acknowledgements,

1 Introduction and ProgrammingPreliminaries,1


l.l Introduction,I
1.2 Softwareand hardware,I
1.3 Mathernaticalsubroutinelibraries,I
1.4 Functionsand subroutines,3
4
1.4.1Arrays as parametersin subroutines,
1.5 Errors, 7
1.5.1Roundoff.7
1.5.2Truncation.8
1.5.3Cancellation, 9
1.6 Conclusions,9
1.7 Further reading,l0

2 Linear AlgebraicEquations,11
2.1 Introduction,I I
2.2 Gaussianelimination" I I
2.2.1Observationson the eliminationprocess,l5
2.3 Equationsolution usingLU factorisation,16
2.3.1 Observationson the solution processby factorisation,20
2.4 Equations with symmetricalcoefficientmatrix, 20
2.4.1 Quadratic form and positive definiteness,24
2.4.2 Cholesky'smetho4 26
2.5 Bandedequations,27
2.6 Compact storagefor variable bandwidths,30
2.7 Pivoting 33
2.7.1lll-conditioning 35
2.8 Equationswith prescribed'variables', 36
2.9 Iterativemethods,38
2.9.1 The iterative process,39
2.9.2Yery sparsesystems, 44
2.9.3The Gauss-Seidel method,44
2.9.4 Successive 48
overrelaxation,
vi CONTENTS

2.10 Gradientmethods,5l
2.10.1The methodof 'steepest descent',5l
2.10.2The method of 'conjugategradients',54
2.10.3Convergence of iterationmethods,56
2.10.4Preconditioning, 56
2.ll Comparisonof directand iterativemethods,57
2.12 Exercises,58
2.13 Further reading,60

3 NonlinearEquations,62
3.1 Introduction,62
3.2 Iterativesubstitution.65
3.3 Multiple roots and other difficulties,67
3.4 Interpolationmethods,68
3.4.1Method of bisection,69
3.4.2Falsepositionmethod,7l
'
3.5 Extrapolationmethods,74
3.5.1Newton-Raphsonmethod,74
3.5.2A modifiedNewton-Raphsonmethod,26
3.6 Accelerationof convergence, 79
3.7 Systemsof nonlinearequations,80
3.7.1Iterativesubstitutionfor systems,80
3.7.2Newton-Raphsonfor systems,82
g6
3.7.3Modified Newton-Raphsonmethodfor systems,
3.8 Exercises,89
3.9 Further reading,91

4 Eigenvalue Equations, 92
4.1 Introduction,92
4.2 Orthogonalityand normalisationof eigenvectors, 93
4.3 Soluticnmethodsfor eigenvalue equations,94
4.4 Vectoriteration,94
4.4.1Shiftediteration,97
4.4.2Shiftedinverseiteration.99
4.5 Calculationof intermediateeigenvalues - dcflation,103
4.6 The generalised eigenvalue problemAx:18x, 105
4.6.1Conversionof generalised problemto standardform, 108
4.7 Transformationmethods,111
4.7.1Commentson Jacobidiagonalisation,l17
4.7.2 Householder's transformationto tridiagonalform, 117
4.7.3 LR transformationfor eigenvaluesof tridiagonal matrices,l2l
4.7.4 l-anczosreduction to tridiagonal form, 124
4.8 Characteristic polynomialmethods,127
4.8.1 Evaluatingdeterminantsof tridiagonalmatriccs,127
4.8.2 The Sturm sequenceproperty, 128
4.8.3 Generalsymmetricmatrices,e.g.band matrices,133
4.9 Exercises. 133
4.10 Further reading,135
5 Interpolationand Curve Fitting, 137
5.1 Introduction,137
CONTENTS

5.2 Interpolatingpolynomials, 137


5.2.1 Lagrangianpolynomials,137
5.2.2 Differencemethods,l4t
5.2.3Splinefunctions,146
5.3 Numericaldifferentiation, 151
5.3.1 Errors in differenceformulae.l5g
5.4 Curve fitting, 159
5.4.1Leastsquares, 159
5.5 Exercises, 164
5-6 Further reading,167

Numerical Integration, 168


6.t Introduction,168
6.2 Newton{otes rules.169
6.2.1Introduction,169
6.2.2 One-pointrule (rectanglerule, n:1), 170
6.2.3Two-point rule (trapeziumrule, n:2), 170
6.2.4Three-pointrule (Simpson'srule, n:3), l7t
6.2.5HigherorderNewton{otes.rules(n>3), l13
6.2.6 Aq,uracy of Newton{otes rules, 173
6.2.6.1Error in rectanglerule, 174
6.2.6.2Enor in trapeziumrule, 174
6.2.6.3Error in Simpson'srule, 174
6.2.7 Summaryof Newton{otes rules,175
6.2.8 Repeatedrules,l?6
6.2.8.1Repeatedtrapeziumrule, 176
6.2.8.2RepeatedSimpson'srule, 177
6.2.9 Remarkson Newton{otes rules,lg0
6.3 Gauss-Legendre rules,180
6.3.1Introduction,180
6.3.2One-pointrule (midpointrule,n:l), lgl
6.3.3Two-point rule, 182
6.3.4Three-pointrule (n:3), 183
6.3.5 Changingthe limits of integration,lg4
6.3.6Accuracyof Gauss-lrgendrerules,lgg
6.3.7 Summaryof Gauss-lrgendrerules,lgg
6.4 Specialintegrationrules,189
6.4.1Introduction,189
6.4.2 Gauss-Laguerre rules,189
6.4.3Gauss{hebyshevrules,192
6.4.4 Fixed weightingcoefficients, 192
6.4.5 Hybrid methods,193
6.4.6 Samplingpoints outsidethe rangeof integration,193
6.5 Multiple inregrals,194
6.5.1Introduction.194
6.5.2 Integrationover a rectangulararea,195
6.5.3 Integrationover a generalquadrilateralarea,200
6.6 Exercises.205
6.7 Further reading,209
viii CONTENTS

7 NumericalSolutionsof Ordinary DifferentialEquations,210


7.1 Introduction, 210
7.2 Definitionsand typesof differentialequations,2l0
7.3 Initial valueproblems,212
7.3.1One-step methods, 213
7.3.1.1Euler'smethod,214 '
7.3.1.2Modified Euler'smethod.216 .
7.3.1.3Midpointmethod,217
7.3.1.4Runge-Kuttamethods,219
7.3.1.5Accuracyof one-step methods,222
7.3.1.6Reductionof high order equations,224
' 7.3.1.7Solutionof simultaneous first order equations,226
7.3.1.80-Methodsfor linearequations, 231
7.3.2Predictor-rorr@tormethods.233
7.3.2.1Euler-trapezoidal method,235
, 7.3.2.2Milne'smethod,236
7.3.2-3Adams-Moulton-Bashforth method.237
7.3.2.4 Ac*uracyof predictor--conectormethods,238
7.3.3Stiff equations,242
7.3.4 Enor propagation- numcrical stabilily, 242
7.3.5Concludingremarkson initial valueproblems,244
7.4 Boundaryvalueproblems,244
7.4.1Finite differencemethods,245
7.4.2Shootingmethods,252
7.4.3Weightedresidualmethods,261
7.4.3.1Collocation,264
7.4.3.2SuMomairL265
7.4.3.3Lr-astsquares,266
7.4.3.4Galerkin'smethod,267
7.4.3.5Concluding remarkson weightedresidualprocedurcs,268

8 Introduction to Partial DifferentialEquations,276


8.1 Introduction,2T6
8.2 Somedefinitions,276
8.3 First order equations,277
8.4 Secondorder equations,281
8.5 Finite differencesin two dimensions.283
8.6 Elliptic systems,
286
8.7 Parabolicsystems, 291
8.7.1Stabilityof finite differences,
292
8.8 Hyperbolicsystems, 295
8.9 Exercises, 298
8.10Further reading,302

APPENDIX 1: Alphabeticdescriptionof subroutinelibrary,303

APPENDIX 2: Alphabeticlistingof subroutinelibraryin FoRTRAN77,313

Index.327
List of Programs

Chapter2
2.1 Gaussianelimination,l3
2.2 Equationsolution by LU factorisation,19
2.3 Symmetricalequationsolutionby LDLT factorisation,23
).4 Symmetricalequationsolutionby Cholesky'smethod,29
2.5 'skyline' solution of symmetricalequationsby Cholesky'smethod,3l
2.6 Equationsolution by LU factorisationwith pivoting,34
2.7 Equationsolutionwith prescribed'variables', 37
2.8 Equationsolution by Jacobiiteration,42
2.9 Equationsolution by Gauss-Seidel iteration,46
2.10Equationsolution by successive overrelaxation,49
2.11Equationsolutionby'steepcstdescent', 52
2.12Equationsolutionby conjugategradients,54

Chapter3
3.1 Simpleiterationfor a nonlinearcquation,66
3.2 Bisectionmethod.70
3.3 Falsepositionmethod,72
3.4 Newton-Raphsonmethod,75
3.5 Modified Newton-Raphsonmethod,78
3.6 Simpleiteration for a systemof equations,8l
3.7 Newton-Raphsonmethod for a systcmof equations,85
3.8 Modified Newton-Raphson rnethod for a systemof equations,88

Chapter 4
4.1 Vectoriterationto find the'largest'eigenvalue,96
4.2 Shiftediteration.98
4.3 Shiftedinverseiteration. 101
4.4 Iterativesolutionof Ax: lBx, 106
4.5 Conversionof Ax:lBx to'standard form', ll0
4.6 Jacobidiagonalisation,I l5
4.7 Householder'sreduction to tridiagonal form, 120
4.8 LR transformation,123
4.9 Lanczosreduction to tridiagonal form, 125
4.10Characteristicpolynomialmethodfor symmetric,positivedefinitetridiagonalmatrices,131

Chapter5
5.1 Interpolationusing Lagrangianpolynomials,140

IX
L I S TO F P R O G R A M S

5.2 Interpolationusingcubicsplinefunctions,150
5.3 Curvefitting using'leastsquares',161

Chapter6
6.1 RepeatedNewton{otes rules,178
6.2 RepeatedGauss-lrgendrerules,187
6.3 Gauss-Laguerre integration,191
6.4 Integrationover a generalquadrilateralarea,203

Chapter7
7.1 One stepmethodsfor a singlefirst order equation,221
7.2 ()ne step methodsfor a systemof first order equations,229
7.3 Predictor{orrector usingAdams-Moulton-Bashforthfourth order method,24o
7.4 Shootingmethodfor a secondorder linear boundaryvalueproblem,253
7.5 shooting methodfor a secondorder nonlinearboundaryvalueproblem,259
Preface

This book is basedon a lecture


coursein numericarmethodsin
by theauthorsto secondyearundergraduates engineeringgiven
(sophomoresf uniors) at the university
of Manchester. The coursehasevolvedover a
numberof yearsinto its present
of formal recturesand practicat'tanas-on,experience;p;;li.,, brend
. majority of students,it wilr constitut" sorving. For the
th. only formar training they wil
the numericartechniques- rec€ivein
which underpin,o -u"t of engineeriig
such it forms a bridge between anarysistoday.As
the classicalmathematicsanl
code-based techniques heavily computer
suchas the finiteerementand boundary
erementmethods.For
:rT:lf:#Ifr:Jf:"iHil:*u' constitute
anintroductio,,,o
thedeeper
study
T h e r ea r e
two mi.
introductoryb""u"1ii;r::ll,i.*",T:111il1ilffi ,T$fir'ilfi l,;:::*;
did not coverthe rangeof materiar
they neeaea.For exampre, few booksincorporate
methodsof weightedresidualsin
theirtreatmentof thesolutionof
equations,arthoughthesemethods ordinarydifferential
are centrarto the understanding
techniques. In order to achievebreadthofcoverage, of finite erement
forcedto be selective. the authorshave inevitablybeen
This book, therefore,describes
analysislikely to be of most use only the aspects of numericar
to engineers, and which can be embodiedin a
year'scourse'No attempt single
is made to catarogue"u".y tno*n
simultaneousequationsor ordinary metnoa for solving
diftrentirr equations.
secondly,althoughmanybooksnow incorporate
computercode,thisis not donein
a systematicor didactic way.
In contrast,the authors
program-writingbasedon the o.ooo* a ph'osophy of
useof subprograms. The compuier
is .oRrn,c,N77' andsothesubprograms languageemproyed
"r" ,t*r*o* FUNCrroNs and susnourrNEs.
this way, the book servesas In
an introduction to the useof powerfur
subroutinelibraries'Everyaspect mathematical
of numericalanalysis*t i"t isl"s"ribed
is illustratedby a compact program in the book
which makes use of a simple library.
FoRTRAN programsand subroutinesdescribed A' the
in this book can fobtained from
publishersin the form of a the
diskette.
The authors are actively invorved
in numericarmodering, usually
elements,both at researchrevel using finite
and io *gin""ring consurtancy. Although
England,both authorshaveconsideraute basedin
e-xierience of engineeringeducation
America, being engineeringgraduates in North
of uC Berkeley,and frequent
visitors to

XI
xir PREFACE

academic symposia. The first author recently spent fifteen months at princeton
University teaching and conducting researchin the area of finite element modellins
of the responseof dams to earthquake loading.

D.V. Griffiths/I.M. Smith


Acknowledgements

The authorsare indebtedto the followingreviewersfor their helpfuland constructive


commentsregardingthe contentsof this book:

W.F. Ames
P.rofessor GeorgiaTech
ProfessorZ.P.Bazant NorthwesternUniversity
Dr D.N. Fenner King's College,London
ProfessorG.M.L. Gladwell Universityof Waterloo
ProfessorJ.G. Hartley GeorgiaTech
ProfessorW. Miller Jr. Universityof Minnesota
ProfessorN. Whitaker Universityof Massachusetts
ProfessorR. White North CarolinaStateUniversity

Thanks also go to Navin Sullivan of BlackwellScientificPublicationsfor his


encouragement in this project,and particularlyfor keepingthingsticking over while
the two authors wereliving on oppositesidesof the Atlantic.
Finally, the authors would like to thank the secretarialstaff of Manchester
UniversityEngineeringDepartmentwho all had a part to play in the preparationof
the manuscript.Particularthanksgo to BarbaraMichniowskiand DoreenDye who
did the majority of the typing, and to Sally Henshallfor the figures.
Introducfionand Programmingpreliminaries

1.1 Introduction
Thereare manyexistingtextsaimedat introducingengineers
to the useof numerical
methods.Increasingly, thesecontain computercode which enabresa particular
problem to be solved.In the presentbook, this idea
is taken to a logicalconclusion,
namelythat the naturalway of learninghow numericalmethods
work is to codethem
for a digital computer,and then to do numericalexperiments.
In order to achievethis
aim efficiently'it is arguedthat it paysto adopta styleof programming
whichfacilitates
transferof expertisefrom one numericaranalysistask to
another.

1.2 Software and hardware

This book containsforty-two computer programs


and thirty-three .ribrary, sub_
programs,whicharewrittenin ronrReN77.While
thislanguagsis not ideal,aswill be
'shown,it is by far
the mostcommonin usein engineering pr*ti"" today,a situation
whichshowsno signof changing.A newversionof ronr*iN,
entirelycompatiblewith
F.RTRAN77, wirl remedy many of its deficiencies
and will soon becomewidely
available.
As to hardware,the only prerequisiteis a machine
capableof compiling and
runningF.RTRAN 77 programs.This embracesthe vastmajorityof computersnow
availablecommercially, from the'pc'range upwardsthroughmedium_sized computers
to 'supercomputers'.

1.3 Mathematicalsubroutinelibraries
Nearly all computermanufacturerssupply some kind
of .library, of mathematical
softwarewith the machine.Thus, while it would be perfectly
feasiltefor eachuserto
write programsto work out the sineof an angle,for example
by summinga series,thisis
a task which occursso frequentrythat it makessenseto
havethe codepermanently
storedin everymachineof that make.In FoRTRAN machines,thelanguage providesfor
about forty 'intrinsic'or 'library' functions:ABs,ACos,
ATMAG, ArNr, ANINT,ASrN,
ArAN, etc.' which enable users to carry out simple
but commonly occurring
mathematical tasks.
2 C H A P T E R1

To supplementthese,most manufacturers will also supply a 'mathematicalsub-


rouiine library' which enablesrather more complex operationsto be undertaken-
solvinglinearsimuitaneous equationsis a commonexample- without the userhaving
to write the cociing.While suchlibrariescan be helpful,particularlywhen they make
bestuseof somespecialliarciivarecapabilitiesof a particularmachine,they tendto be
limited in extentand oftenare not 'portable',i.e. transferrable
from one machineto
another.

Tabie1.1.Contents
of nec mathematical
subroutine
library
'Chapter'
Subject area Nature

AO2 Complexarithmetic Utility routine


(3) * C02 Znrosof polynomials
C0.5 Rootsof one or mcre transcendental
equations
C06 Suminationof series
(6) * D01 Quadrature
(7) * D02 Ordinary differentialequations
(8) + D03 Partial differentialequations
(5) + DM Numericaldifferentiation Determination
D05 Integralequations Numerical
(5) * EOl Interpolation analysis
(5) * F,02 Curveand softwarefitting
804 Maximisingor minimisinga function
(2) * F01 Matrix operationsincludinginversion
(4) + F02 Eigenvaluesand eigenvectors
(2) * F03 Determinants
(Z) * F04 Simultaneous linear equations
F05 Orthogonalisation

G01 Simplecalculations on statisticaldata


GO' Correlation and regressicnanalysis
G(4 Analysesof variance
G05 Randomnurnbergenerators Statistical
G07 Univanate estimation analysis
G08 Nonparametric statistics
Gtl Contingency table analysis
Gl3 Time seriesanalysis
H Operations research

M01 Sorting
POl Error Trapping
S Approximationsof SpecialFunctions Utility
X01 MathematicalConstants routines
X02 MachineConstants
XO3 Innerproducts
X04 Input/Output Utilities

* Area covered in the present text


( ) Chapter in this book deallng vrith this topic
i
L NN D P R O G R A M M I N GP R E L I M I N A R I E S
I N T R O D U C T I OA
!
1:
For thisreason,organisations haveevolvedwhichsupportmathematical subroutine
l good example is the wnc
librariesavailablefor useon many differentcomputers.A
mathematicalsubroutinelibrary, containingover 600 subroutines.Theseattemptto
covera wideareaof numericalapplications, andareorganisedinto'chapters'whichare
listedin Tablel.l.
t 'deterministic'numerical
I These chapterscan be very broadly classifiedinto
i
analyses, statisticalanalysesand utility routines.The presentbook dealsonly with the
I
l' first oftheseclassesand eventhenwith a subset,asterisked in the table.Preceding each
asterisk,in parentheses,is thechapterin the presentbook whichformsan introduction
to the sametopic.
Otherlibrarieswith whichstudents maybefamiliarareIMsL,MATLAB andLINPAcK
and ersrecx, the last two being sub-libraries dealingspecifically with linear algebra
and eigenvalueanalysesrespectively.
. It canbe seenthat the majorityof deterministicanalyses methodswill be dealtwith
in the following chapters. The selection is governed by limitations of spaceand of
teachingtime in typical courses.The book is also directed towards coverageof
probablythc mostimportantareaof numericalanalysisconc€rningengineers, namely
the solutionof differentialequations.
In the chaptersthat follow, we shallthereforeillustratehow simplemathematical
subroutinesareconstructedand how thesearethenassembled to form smallcomputer
programs to addressvarious numerical analysis tasks. This will serve as an
introduction for studentsand engineersto the use of much more comprehensive
i
softwaresuchas the Nec mathematicalsubroutinelibrary.
l' Beforewriting any programs,we must first illustratehow subroutinescan bestbe
constructedto be'portable' betweenone userprogram and another-

t
I
1.4 Functionsand subroutines
I
In the previoussection,we remarkedthat the FoRTRAN languagecontainsa list of
'intrinsic' or 'library functions'for carrying out simple tasks like taking sinesand
I
I
cosines of angles.A runcrloN in rontRaNis a specialsubprogramhavinga specific
'main'
structure,and any numberof thesecan be appendedby programmersto their
programs.
?
Suppose,for example,we wishedto refermany timesin a'main'program to the
t functionf(x):3x2+15x-23.To savewriting all of the algebraout eachtime,we
I couldcreatea FoRTRAN FUNcrIoN.as follows:

FUNCTION F(X)
c
c THIS IS AN EXA},IPLE OF A FUNCTION CALLED F
THE INPUT IS X
c
F : 3 . O * X * X + 1 5 .0 * X - 2 3 . 0
RETURN
END

I
C H A P T E R1

Then in the main program, as long as the'argument' of F has a value, we can refer to
F as many times as we like, for example in statementslike A: F(xl)*F(X2)/F(X3). The
'returns' a single quantity (the
FUNCTToN subprogramis particularly simple since it
'called' from that main
value of the function /(x)) to the main prograrn each time it is
program.
If more than one quantity is to be returned to the main program from a subprogram
call (evenif the argument,although a singlename, is an array) then a more complicated
that
type of subprogramcalleda suBRourlNEmust be used.This also has a name' but
'parameters' are
name cannot be used in cxpressions.Instead, Several arguments or
used to pass information into and out of the subprogram'
As an example,our ruNcttON subprogramcould be written as a SUBRoUTINe in the
following way:

a
SUBROTJITINEFI,'N(F, X)
c
THIS IS AN EXAHPLE OF A SUBROUTINE CALLED T'UN
c THE TNPUT TS X AND THE OUTPUT IS F
c
F = 3 . O * X * X + 1 5 .O * X - 2 3 . 0
RETURN
END

In the main program, we would then have to'call'the susnourtNs with its different
arguments in order to work out the previously determined A, for example:

CALL FUN(F1,X1)
CALL FUN(F2,X2)
CALL FrJN(F3,X3)
A=F1*F2 / F3

In Chapters2 to 7 whichfollow,the useof a sUBRoUrtNrratherthan a FUNCTIoN


will be the norm, sinceour parameterswill often be arrays.The use of arrays in this
way causes some additional complications in ronrnlN 77 which are now
described.

in subroutines
1.4.1Arrays as parameters

In poRrnlN 77 main programs,arraysmust have siies which are known beforethe


program is compiled.Thus a typical main program might havea structure

PROGRAM DECI,AR

DECI,ARATION OF ARRAY SIZES


c
R E A L A ( 1 O O ) , 8 ( 1 O O O5, 0 ) , C ( 5 0 , 1 0 0 )

STOP
END
I N T R O D U C T I OANN D P R O G R A M M I N GP R E L I M I N A R I E S

In order to avoid the need to be forever altering lots of parameters of arrays for
problems of different sizes, the language allows a pARAMETEnstatement which
alleviates this difficulty somewhat. Using this statement, the above program can be
written:

PROGRAM DECLAR
c
U DECI,ARATTON OF ARRAY SIZES USTNG PARAMETER STATEMENT

P A R A M E T E R( I A = 1 0 0 , I B = 1 0 0 0 r I c = 5 0 )
c
REALA(rA),8(rB, IC),C(rc, rA)

STOP
END

ln susRourtNEs which usearraysas parameters,it is necessary for thesearraysto be


compatibly'mapped'onto themainprogramfixedstoragearea.And yet thepurposeof
a suBRourINeis thatit shouldbe'portable',that is it shouldbe ableto be transferred
freelybetweenuserprogramswithout any restrictionsrelatedto theseprograms'main
storagestrategy.
Considerfirsta susnourlNEinvolvingonly one-dimensional arrays.We shallsee
thata commontaskisto findthescalaror'dot'productDorPR of two vectors, sayvl
and v2. within the susnourrNg,vl and v2 haveto be'declared'. but sinceall the
subprogramhasto do to carryout the mappingis to locatethe first elementin storeof
eachof thevectors,
i.e.vl(l) andv2(1),FoRTRAN 77 allowsusto declarethemasvl(*)
and V2(*)respectively.Thus the suBRourrNEcan be written:

s u B R o r . J : u N E v D o T v ( V 1 , V 2 , D O T P R ,N )
c
DOT PRODUqT V1*V2

REAL V1(*),V21*1
DOTPR: 0.0
DO 1 I : 1,N
I DoTPR = DoTPR + v1(r)*V2(r)
RETURN
END

Theinput parametersarethenamesof the vectorsto bemultiplied,Vl andV2, together


with the lengthof thevectors,N. The output consistsof the dot product,namedasthe
singleparameterDOTPR. Note that the actualsizeof Vl and V2 in the main program
is irrelevantas long as it is greaterthan, or equal to N.
The situation becomesrather more complicated when arrays processedby
subprograms havetwo or moredimensions, asshownin Fig. 1.1.In ronrneN 77,arrays
arestoredby columns.That is,for a two-dimensionalarrayA, the elementsarestored
in theorderA(1,l), A(Z l), ... A(M, 1),... A(IA, 1),A(1,2),A{2,2)... A(M,2) ... A(IA,2),
etc. Thus, for appropriatemapping betweenmain program and subprogram,the
suBRourrNE hasto pickup notjust thefirstelementof arrayA, namelyA(1,l), but also

Anda mungkin juga menyukai