ebook img

Object-oriented Programming via Fortran 90/95 PDF

355 Pages·2003·2.3 MB·English
by  Ed Akin
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Object-oriented Programming via Fortran 90/95

Object-oriented Programming via Fortran 90/95 ED AKIN RiceUniversity CAMBRIDGE UNIVERSITY PRESS Cambridge,New York,Melbourne,Madrid,Cape Town,Singapore,São Paulo Cambridge University Press 40 West 20th Street,New York,NY 10011–4211,USA www.cambridge.org Information on this title:www.cambridge.org/9780521524087 ©Ed Akin 2003 First published 2003 Reprinted 2003 Printed in the United States of America Acatalogue record for this book is available from the British Library. ISBN-13 978-0-521-52408-7 paperback ISBN-10 0-521-52408-3 paperback P1:FCH/SPH P2:FCH/SPH QC:FCH/TKJ T1:FCH CB496-FM CB496-Akin September27,2002 18:0 Contents Preface pageix One. ProgramDesign 1 1.1 Introduction 1 1.2 ProblemDefinition 4 1.3 ModularProgramDesign 6 1.4 ProgramComposition 11 1.5 ProgramEvaluationandTesting 18 1.6 ProgramDocumentation 21 1.7 Object-OrientedFormulations 21 1.8 Exercises 24 Two. DataTypes 26 2.1 IntrinsicTypes 26 2.2 User-DefinedDataTypes 28 2.3 AbstractDataTypes 31 2.4 Classes 33 2.5 Exercises 35 Three. Object-OrientedProgrammingConcepts 36 3.1 Introduction 36 3.2 Encapsulation,Inheritance,andPolymorphism 37 3.3 Object-OrientedNumericalCalculations 42 3.4 Discussion 51 3.5 Exercises 51 Four. FeaturesofProgrammingLanguages 56 4.1 Comments 57 4.2 StatementsandExpressions 57 4.3 FlowControl 63 4.4 Subprograms 76 4.5 InterfacePrototype 84 4.6 CharactersandStrings 85 4.7 User-DefinedDataTypes 92 4.8 PointersandTargets 99 4.9 AccessingExternalSourceFilesandFunctions 102 P1:FCH/SPH P2:FCH/SPH QC:FCH/TKJ T1:FCH CB496-FM CB496-Akin September27,2002 18:0 4.10 ProceduralApplications 103 4.11 Exercises 115 Five. Object-OrientedMethods 119 5.1 Introduction 119 5.2 TheDrillClass 119 5.3 GlobalPositioningSatelliteDistances 121 5.4 Exercises 136 Six. InheritanceandPolymorphism 137 6.1 Introduction 137 6.2 SampleApplicationsofInheritance 137 6.3 Polymorphism 142 6.4 SubtypingObjects(DynamicDispatching) 152 6.5 Exercises 156 Seven. OODataStructures 157 7.1 DataStructures 157 7.2 Stacks 157 7.3 Queues 159 7.4 LinkedLists 164 7.5 Direct(Random)AccessFiles 175 7.6 Exercises 177 Eight. ArraysandMatrices 178 8.1 SubscriptedVariables:Arrays 178 8.2 Matrices 195 8.3 Exercises 206 Nine. AdvancedTopics 209 9.1 ManagingDynamicMemory 209 9.2 Large-ScaleCodeDevelopment 216 9.3 NonstandardFeatures 227 9.4 Exercises 227 AppendixA. Fortran90Overview 229 A.1 ListofLanguageTables 229 A.2 AlphabeticalTableofFortran90IntrinsicRoutines 246 A.3 SyntaxofFortran90Statements 258 AppendixB. SelectedExerciseSolutions 277 B.1 Problem1.8.1:CheckingTrigonometricIdentities 277 B.2 Problem1.8.2:Newton–RaphsonAlgorithm 278 B.3 Problem1.8.3:GameofLife 278 B.4 Problem2.5.1:ConversionFactors 280 B.5 Problem3.5.3:CreatingaVectorClass 282 B.6 Problem3.5.4:CreatingaSparseVectorClass 289 B.7 Problem3.5.5:CreatinganInventoryObject 297 B.8 Problem4.11.1:CounttheLinesinanExternalFile 299 B.9 Problem4.11.3:ComputingCPUTimeUsage 300 B.10 Problem4.11.4:ConvertingaStringtoUppercase 301 B.11 Problem4.11.8:ReadTwoValuesfromEachLineofanExternalFile 301 P1:FCH/SPH P2:FCH/SPH QC:FCH/TKJ T1:FCH CB496-FM CB496-Akin September27,2002 18:0 B.12 Problem4.11.14:Two-lineLeast-squareFits 301 B.13 Problem4.11.15:FindtheNextAvailableFileUnit 305 B.14 Problem5.4.4:PolymorphicInterfacefortheClass‘Position Angle’ 306 B.15 Problem5.4.5:BuildinganObjectInventorySystem 307 B.16 Problem6.4.1:UsingaFunctionwiththeSameNameinTwoClasses 312 B.17 Problem6.4.3:RevisingtheEmployee–ManagerClasses 312 B.18 Problem8.3.5:DesignaTridiagonalMatrixClass 312 B.19 Problem9.1:CounttheIntegerWordMemoryLeak 317 AppendixC. CompanionC++Examples 319 C.1 Introduction 319 Bibliography 327 GlossaryofObject-OrientedTerms 329 Index 335 P1:FCH/SPH P2:FCH/SPH QC:FCH/TKJ T1:FCH CB496-FM CB496-Akin September27,2002 18:0 Preface There has been an explosion of interest in, and books on, object-oriented programming (OOP).Whyhaveyetanotherbookonthesubject?Inthepastabasiceducationwasin- tendedtoresultinmasteryofthethreer’s:reading,’riting,and’rithmetic.Todayasound education in engineering programming leads to producing code that satisfies the four r’s: readability,reusability,reliability,andrealefficiency.Althoughsomeobject-orientedpro- gramminglanguageshavesomeoftheseabilities,Fortran90/95offersallofthemforengi- neeringapplications.Thus,thisbookisintendedtotakeadifferenttackbyusingtheFortran 90/95languageasitsmainOOPtool.Withmorethan100pureandhybridobject-oriented languagesavailable,onemustbeselectiveindecidingwhichonesmerittheeffortoflearning toutilizethem.TherearemillionsofFortranprogrammers,andsoitislogicaltopresent the hybrid object-oriented features of Fortran 90/95 to them to update and expand their programming skills. This work provides an introduction to Fortran 90 as well as to OOP concepts.Evenwiththecurrentrelease(Fortran95)wewilldemonstratethatFortranoffers essentially all of the tools recommended for OOP techniques. It is expected that Fortran 200X will offer additional object-oriented capabilities such as declaring “extensible” (or virtual)functions.Thus,itisexpectedthatthetoolslearnedherewillbeofvaluefarintothe future. Itiscommonlyagreedthatthetwo-decade-oldF77standardforthelanguagewasmiss- ingseveralusefulandimportantconceptsofcomputersciencethatevolvedandweremade popular after its release, but it also had a large number of powerful and useful features. ThefollowingF90standardincludedmanyimprovementsthathaveoftenbeenoverlooked byprogrammers.ItisfullycompatiblewithalloldF77standardcode,butitdeclaredsev- eralfeaturesofthatstandardobsolete.Thatwasdonetoencourageprogrammerstolearn bettermethodseventhoughthestandardstillsupportsthosenowobsoletelanguagecon- structs.TheF90standardscommitteebroughtintothelanguagemostofthebestfeaturesof othermorerecentlanguageslikeAda,C,C++,Eiffel,andsoforth.Inpartthoseadditions included structures, dynamic memory management, recursion, pointers (references), and abstractdatatypesalongwiththeirsupportingtoolsofencapsulation,inheritance,andthe overloadingofoperatorsandroutines.Equallyimportantforthoseinvolvedinnumerical analysis,theF90standardaddedseveralnewfeaturesforefficientarrayoperationsthatare verysimilartothoseofthepopularMatlab environment.Mostofthosefeaturesinclude additional options to employ logical filters on arrays. All of the new array features were intendedforuseonvectororparallelcomputersandallowprogrammerstoavoidthebad habitofwritingnumerousserialloops.Thecurrentstandard,F95,wentontoaddmorespe- cificparallelarraytools,provided“pure”routinesforgeneralparalleloperations,simplified P1:FCH/SPH P2:FCH/SPH QC:FCH/TKJ T1:FCH CB496-FM CB496-Akin September27,2002 18:0 theuseofpointers,andmadeafewuser-friendlyrefinementsofsomeF90features.Indeed, atthistimeonecanviewF90/95astheonlycross-platforminternationalstandardlanguage forparallelcomputing.Thus,Fortrancontinuestobeanimportantprogramminglanguage that richly rewards the effort of learning to take advantage of its power, clarity, and user friendliness. WebeginthatlearningprocessinChapter1withanoverviewofgeneralprogramming techniques.Primarilytheolder“procedural”approachisdiscussedthere,butthechapter closes with an outline of the newer “object” approach to programming. An experienced programmer may want to skip directly to the last section of Chapter 1, where we outline someobject-orientedmethods.InChapter2,weintroducetheconceptoftheabstractdata types and their extension to classes. Chapter 3 provides a fairly detailed introduction to theconceptsandterminologyofobject-orientedprogramming.Amuchlargersupporting glossaryisprovidedasasupplement. Forthesakeofcompleteness,Chapter4introduceslanguage-specificdetailsofthetopics discussedinthefirstchapter.TheFortran90/95syntaxisusedthere,butinseveralcasescross referencesaremadetosimilarconstructsintheC++languageandtheMatlabenvironment. Although some readers may want to skip Chapter 4, it will help others learn the Fortran 90/95syntax,ortheymayreadrelatedpublicationsthatuseC++orMatlab.Allofthesyntax ofFortran90isalsogiveninanappendix. Since many Fortran applications relate to manipulating arrays or doing numerical ma- trixanalysis,Chapter5presentsaverydetailedcoverageofthepowerfulintrinsicfeatures Fortran90hasaddedtoprovideformoreefficientoperationswitharrays.Ithasbeendemon- stratedintheliteraturethatobject-orientedimplementationsofscientificprojectsrequiring intensiveoperationswitharraysexecutemuchfasterinFortran90thaninC++.SinceFortran 90wasdesignedforoperationsonvectorandparallelmachines,thatchapterencouragesthe programmertoavoidunneededserialloopsandtoreplacethemwithmoreefficientintrinsic arrayfunctions.ReadersnotneedingtousenumericalmatrixanalysismayskipChapter5. Chapter 6 returns to object-oriented methods with a more detailed coverage of using object-orientedanalysisandobject-orienteddesigntocreateclassesanddemonstrateshow to implement them using OOP in Fortran 90. Additional Fortran 90 examples of inheri- tance and polymorphism are given in Chapter 7. Object-oriented programs often require the objects to be stored in some type of “container” or data structure such as a stack or linkedlist.Fortran90object-orientedexamplesoftypicalcontainersaregiveninChapter8. SomespecializedtopicsformoreadvancedusersaregiveninChapter9,andsobeginning programmersmayskipthatchapter. To summarize the two optional uses of this text: it is recommended that experienced FortranprogrammerswishingtolearntouseOOPcoverChapters2,3,6,7,8,and9,whereas personsstudyingFortranforthefirsttimeshouldcoverChapters1,2,3,and.Anyoneneeding tousenumericalmatrixanalysisshouldalsoincludeChapter5. AnOOglossaryisincludedtoaidinreadingthistextandthecurrentliteratureonOOP. Another appendix on Fortran 90 gives an alphabetical listing of its intrinsic routines, a subject-basedlistofthem,adetailedsyntaxofalltheF90statements,andasetofexamples demonstratingtheuseofeverystatement.Selectedsolutionsformanyoftheassignments are included in another appendix, along with comments on those solutions. The final ap- pendixgivestheC++versionsofseveraloftheF90examplesinthetext.Theyareprovided asanaidtounderstandingotherOOPliterature.SinceF90andMatlabaresosimilar,the correspondingMatlabversionsoftendirectlyfollowtheF90examplesinthetext. P1:FCH/SPH P2:FCH/SPH QC:FCH/TKJ T1:FCH CB496-FM CB496-Akin September27,2002 18:0 Acknowledgments Weareallindebtedtothehundredsofprogrammerswholaboronvariousstandardscommit- teestoimproveallprogramminglanguagescontinuously.Chapter1isamodificationofin- troductoryprogrammingnotesdevelopedjointlywithProf.DonJohnsonatRiceUniversity. IwouldliketothankTinsleyOdenandtheTexasInstituteforComputationalMathematics forgenerouslyhostingmysabbaticalleave,duringwhichmostofthisworkwasdeveloped, and Rice University for financing the sabbatical. Special thanks go to my wife, Kimberly, withoutwhosesupportandinfinitepatiencethisbookwouldnothavebeencompleted. Source Codes AlloftheprogramexamplesandselectedsolutionsareincludedontheCD-ROMprovided withthebook.TobereadableonvariousplatformstheyhavebeenwrittenwiththeISO9660 standardformat.AdditionalfilesareprovidedtorelatetheISOstandardshortfilenames tothefull-lengthprogramnamesusedinthebook.Ofcourse,thesourcefileswillhaveto beprocessedthroughaFortran90or95or2000compilertoformexecutables.Allofthe (cid:2) figuresarealsoprovidedasencapsulatedPostScriptR files. EdAkin,RiceUniversity,2002 P1:FCH/SPH P2:FCH/SPH QC:FCH/TKJ T1:FCH CB496-01 CB496-Akin September13,2002 15:51 CHAPTER ONE (cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1)(cid:1) Program Design 1.1 Introduction Theprogrammingprocessissimilarinapproachandcreativitytowritingapaper.Incompo- sition,youarewritingtoexpressideas;inprogramming,youareexpressingacomputation. Both the programmer and the writer must adhere to the syntactic rules (grammar) of a particularlanguage.Inprose,thefundamentalidea-expressingunitisthesentence;inpro- gramming,twounits–statementsandcomments–areavailable. Composition,fromtechnicalprosetofiction,shouldbeorganizedbroadly,usuallythrough anoutline.Theoutlineshouldbeexpandedasthedetailiselaboratedandthewholereex- amined and reorganized when structural or creative flaws arise. Once the outline settles, youbegintheactualcompositionprocessusingsentencestoweavethefabricyouroutline expresses.Clarityinwritingoccurswhenyoursentences,bothinternallyandglobally,com- municate the outline succinctly and clearly. We stress this approach here with the aim of developingaprogrammingstylethatproducesefficientprogramshumanscaneasilyunder- stand. Toagreatdegree,nomatterwhichlanguageyouchooseforyourcomposition,theidea canbeexpressedwiththesamedegreeofclarity.Somesubtletiescanbebetterexpressedin onelanguagethananother,butthefundamentalreasonforchoosingyourlanguageisyour audience:peopledonotknowmanylanguages,andifyouwanttoaddresstheAmerican population,youhadbetterchooseEnglishoverSwahili.Similarsituationshappeninpro- gramminglanguages,buttheyarenotnearlysocomplexordiverse.Thenumberoflanguages isfarfewer,andtheirdifferencesminor.Fortranistheoldestlanguageamongthoseinuse today. The C and C++ languages differ from it somewhat, but there are more similarities thannot(seeBar-David[6],BartonandNackman[7],Hanly[22],Hubbard[24],andNielsen [30]). Matlab,writteninCandFortran,wascreatedmuchlaterthanthesetwo,andits structureissosimilartotheothersthatitcaneasilybemastered(seeHanselmanandLittle- field[23],andPratap[33]).TheC++languageisanextensionoftheClanguagethatplacesits emphasisonobject-orientedprogramming(OOP)methods.Fortranaddedobject-oriented capabilitieswithitsF90standard,andadditionalenhancementsforparallelmachineswere issuedwithF95(seeAdamsetal.[1],Gehrke[17],Hahn[21],Kerrigan[25],andPressetal. [34]). TheFortran200Xstandardisplannedtocontainmoreuser-friendlyconstructsfor polymorphismandwillthusenhanceitsobject-orientedcapabilities.Thiscreationofanew languageanditssimilaritytomoreestablishedonesarethisbook’smainpoints:morecom- puterprogramminglanguageswillbecreatedduringyourcareer,butthesenewlanguages willprobablynotbemuchdifferentthanonesyoualreadyknow.Whyshouldnewlanguages P1:FCH/SPH P2:FCH/SPH QC:FCH/TKJ T1:FCH CB496-01 CB496-Akin September13,2002 15:51 2 ProgramDesign evolve?InthecaseofMatlab,thedesiretoexpressmatrix-likeexpressionseasilymotivated itscreation.ThedifferencebetweenMatlabandFortran90isinfinitesimallysmallcompared withthegapbetweenEnglishandSwahili. Animportantdifferencebetweenprogrammingandcompositionisthatinprogramming you are writing for two audiences: people and computers. As for the computer audience, whatyouwriteis“read”byinterpretersandcompilersspecifictothelanguageyouused. Theyareveryrigidaboutsyntacticrules,andperformexactlythecalculationsyousay.Itis likeadocumentyouwritebeingreadbythemostdetailed,pickypersonyouknow;every pronounisquestioned,andiftheantecedentisnotperfectlyclear,thentheythrowuptheir hands,rigidlydeclaringthattheentiredocumentcannotbeunderstood.Yourpickyfriend mightinterpretthesentence“Pickyouupateight”tomeanthatyouwillliterallylifthim orheroffthegroundatprecisely8o’clockandwillthendemandtoknowwhetherthetime isinthemorningorafternoonandwhatthedateis. Humansdemandevenmorefromprograms.Thisaudienceconsistsoftwomaingroups whosegoalscanconflict.Thelargerofthetwogroupsconsistsof users.Userscareabout howtheprogrampresentsitself,itsuserinterface,andhowquicklytheprogramrunsthat is, how efficient it is. To satisfy this audience, programmers may use statements that are overlytersebecausetheyknowhowtomaketheprogrammorereadablebythecomputer’s compiler,enablingthecompilertoproducefasterbutlesshuman-intelligibleprograms.This approach causes the other portion of the audience–programmers–to boo and hiss. The smaller audience, of which you are also a member, must be able to read the program to enhanceorchangeit.Acharacteristicofprogramsthatfurtherdistinguishesitfromproseis thatyouandotherswillseektomodifyyourprograminthefuture.Forexample,inthe1960s, whenthefirstversionofFortranwascreated,usefulprogramsbytoday’sstandards(suchas matrixinversion)werewritten.Backthen,theuserinterfacepossibilitieswerequitelimited, andtheuseofvisualdisplayswaslimited.Thirtyyearslater,youwould(conceivably)want totakeanoldprogram,andprovideamodernuserinterface.Iftheprogramisstructurally sound(agoodoutlineandorganizedwell)andiswellwritten,reusingthe“good”portions iseasyaccomplished. Thethree-audiencesituationhaspromptedmostlanguagestosupportbothcomputer- andhuman-oriented“prose.”Theprogram’smeaningisconveyedbystatementsandiswhat thecomputerinterprets.Humansreadthispart,whichinvirtuallyalllanguagesbearsastrong relationshiptomathematicalequations,andalsoreadcomments.Commentsarenotreadby thecomputeratallbutaretheretohelpexplainwhatmightbeexpressedinacomplicated waybyprogramminglanguagesyntax.Thedocumentorprogramyouwritetodayshould beunderstandabletomorrow,notonlybyyou,butalsobyothers.Sentencesandparagraphs should make sense after a day or so of gestation. Paragraphs and larger conceptual units shouldnotcontainassumptionsorleapsthatconfusethereader.Otherwise,thedocument youwriteforyourselforothersservesnopurpose.Thesameistruewithprogramming;the program’sorganizationshouldbeeasytofollow,andthewayyouwritetheprogram,using bothstatementsandcomments,shouldhelpyouandothersunderstandhowthecomputation proceeds. The existence of comments permits the writer to express the program’s outline directlyintheprogramtohelpthereadercomprehendthecomputation. These similarities highlight the parallels between composition and programming. Dif- ferences become evident because programming is, in many ways, more demanding than prosewriting.Ononehand,thecomponentsandstructureofprogramminglanguagesare far simpler than the grammar and syntax of any verbal or written language. When read- ingadocument,youcanfigureoutthemisspelledwordsandnotbebotheredaboutevery littleimprecisionininterpretingwhatiswritten.Ontheotherhand,simpleerrors,akinto

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.