Transcription of Lecture - Virginia Tech
1 LectureNotesIntroductiontoFortran95andNu mericalComputingAJump-StartforScientists andEngineersAdrianSanduComputerScienceDe partment,MichiganTechnologicalUniversity Reproductionof(partsof)thisdocumentisper missibleonlywithauthor' ,20012c AdrianSandu, :\Fortran90 Programming"byEllis,PhilipsandLahey,Addi son-Wesleypublishingcompany,1994;\Fortra n90 CourseNotes" , ,1997;\Elementarynumericalanalysis" ,2ndedition,JohnWiley&Sons,Inc, AdrianSandu, (optional),followedbytheprogramname(also otional);itendswiththekeywordend(require d),followedbyprogramNameProg(optional).p rogram<name>declarationsexecutablecodeend[program<name>]Opena \helloworld"program:!my rstFortranprogramprogramhelloprint ,'HelloWorld!' ,whichdescribethe\freesourceform". statementscanbegininanycolumn; multiplestatementsonalineareallowed;they havetobeseparatedbysemicolon\;" anexclamationmark\!"inanycolumnisthebegi nningofacomment;therestofthelineisignore dbythecompiler; astatementcanbecontinuedonthefollowingli nebyappendinga\&" ,theabovecodefragmentcouldbewritteninfre esourceformas56c AdrianSandu, !
2 Thisisfree formtemp=x;x=y;y=temp!Swapxandywrite(6, )'xandyare=',&x,y!PrintxandyForback-comp atibilitywithFortran77,Fortran90acceptsa \ xedsourceform".Inshort,the xedsourceformrequirementsare: alllinesofcodestartinthe7th(orhigher)col umn;the rst6columnsarereservedforlabels,contin-u ationcharacters,etc. eachstatementiswrittenonaseparateline( ,statementsareseparatedbynewlines);astat ementcanbecontinuedonthenextlinebywritin g(any)characterinthe5thcolumnofthenewlin e; commentlinesstartwithaCinthe 's,wheneachlineofcodewaspunchedonapaperc ard(\punchedcard"). ,apunchedcardhadtobealigned,checkedifiti sanewstatementoracontinuationofthelast,i fitisacomment, rst6columns.(Amillion-linecode,quitecomm ontoday,onpunchedcards,neededatrucktobec arriedfromonecomputertoanother).Forexamp le,afragmentofaFortran90programin xedsourceform(infact,Fortran77program)ca nbe:C This is xed formC Swapxandytemp=xx=yy=tempC Printxandywrite(6, )'xandyare=', x,yOurcompiler(f90)willconsidertheprogra mtobein xedsourceformatifthesource lehastheextension\.
3 F"(forexample, ).Thecompilerwillconsidertheprogramtobei nfreesourceformatifthesource lehastheextension\.f90"(forexample, ). ers,whichobeythefollowingrestrictions: containupto31characters; the rstcharactermustbealetter; namesarecase-insensitive(nodistictionbet weenupperandlowercase).c AdrianSandu, , \bind"thevariablename(identi er)totheaddressofthereservedmemoryspace; thecontentofthereservedbyteswillholdthev ariable' (default)datatypesinFortran:character,lo gical,integer,real(singleprecision), :integerI,J,Korinteger::I,J,KAnintegerca nbedeclaredandinitializedwithinteger::I= 1 Normally,whentheprogramisloadedinmemory, thecontentsofthedeclaredvariablesareunde ned(somecompilersmaysetthemto0bydefault) .Withinitialization, (whosevaluecannotbechangedlaterintheprog ram)canbedeclaredwithintegerMAXIMUM parameter(MAXIMUM=340)orwithinteger,para meter::MAXIMUM=340 Theplainformofdeclaration,andthetwo-stat ementparameterdeclarationcomefromF77, \::"formisspeci ( ,whenisintegerandparameter, ) :characterCorcharacter::CForastringofcha racters,wecanspecifythelengthand(optiona lly)initializeitascharacter(len=7)::LOGI NA gainweseethat,ifwewanttospecifymorethano neattribute(here,characterandlength) (PARAMETER)characters/strings,inwhichcas eweusethedeclarationcharacter(len=8),par ameter::LOGIN="johndoe"8c AdrianSandu, (theF77two-statementformisalsoacceptable ).
4 Heretheinitializationvalueis6-characterl ong,soitwillbepaddedby2blanksto ,iftheinitializationvaluewastoolong, ,wemayletthecharactervariableassumethele ngthoftheinitializationstringwithcharact er(len= ),parameter::LOGIN="johndoe",PASSWORD="m ichigantech"HereLOGIN willbe7-character, (forback-compatibilitywithF77):character 8::LOGINTheLENattributecanbeoverridenbya attributeinastringdeclarationasfollows:c haracter(len=8)::LOGIN,PASSWORD 12 HereLOGIN isastringof8characters, ; ,itispossibletodeclarea10 10matrixwhoseelementsare6-characterlongs trings:character(len=6),dimension(10,10) ::AAstringcanbesplitaccrosslinesbyadding anampersand& "michig&n&antech" ,Y,PIorreal::X,Y,PIstatethatX,YandPIares ingleprecision (whosevaluecannotbechangedsubsequently)m aybedeclaredwithrealPIparameter(PI= )orwithreal,parameter::PI= (seeabove),orfordeclarationsplusinitial- izationsreal::X= AdrianSandu, rstimplicitnone!
5 ::R,Pi,a,pPi= ,'Pleasegiveradius:'read ,Ra=Pi R! isexponentationp= Pi Rprint ,'Area=',a,'Perimieter=',pendprogram ,Y,PIordoubleprecision::X,Y,PIstatethatX ,YandPIaredoubleprecision ,Worcomplex::Z,WAFortrancomplexvariablei s(andisstoredas)apairofreal(singleprecis ion oatingpoint)variables(therealandtheimagi narypart,ofcourse).Forexample,todeclarea ndinitializethecomplexconstant2+3iweusec omplex,parameter::Z=( , ) (Boolean)variablesaredeclaredaslogicalQ, Porlogical::Q,PTheycantakeonly(oneof)two possiblevalues:trueorfalse(written,inFor trannotation,. ).Adeclarationwithinitializationmaylookl ikelogical::Q=.TRUE.,P=. AdrianSandu, [;hattribute listi]::&[;hvariablei[=hvaluei]]<attribute list>containsattributeslikePARAMETER,SAVE,INT ENT,POINTER,TARGET,DI-MENSION, , ,J,X, ;rather,itwillautomaticallydeclareI,Jasi ntegersandX, rstletterI,J,K,L,MorNareconsideredINTEGE R-s, !InF90implicitdeclarationsarepermitted, ,theiruseisaverybadprogram-minghabit,asi tcanmaskprogrammingerrors, ,amisspellingofavariablenamewillresultin anewvariabledeclaration,whichcanbefurthe rassignedetc, ( )isdo30i= <statements>30continueInsteadofaDOloop,becauseofthem isprints,wewillendupwithanewrealvariable , ,wewillalwaysdisabletheimplicitdeclarati onsbyplacingthecommandimplicitnoneasthe rstlineafteranyUSEstatements( ).
6 Withthiscommandinplace, + , , ,Znew=Zold+2 erentmeaningthanmathematicalequality(her e,themathematicalrelationZ=Z+2:0isanequa tionwithoutsolution).c AdrianSandu, ::a,bNUMERICTYPE::[a]hnumericaloperatori bFortran,likeanyotherlanguage,de ,subtraction,multiplication,divisionande xponentiationoperatorsaredenoted+; ; ;=;and ( +2:1or 2:1)ordyadic( :1 3:4) , :3 3:14,butnot( 2:3) 3 erentnumericaltypescanbeused(willseelate r),butweusuallycannotmixnumericalandchar acter, ; ,anumbercanberaisedtoanintegerpowerY=X 4;Z=X ( 6)Bothexponentvalues4, ,weneedtouseeitherdecimalpointnotationor scienti cnotation(similarto oatingpointnotationbase10:wehaveamantiss a,followedbyanexponentof10;theexpenentis precededbyE)Y=X+ + +1 Fordoubleprecisionconstants,wealwaysuses cienti cnotation,butnowtheexponentmarkerEisrepl acedbyD,fromdouble:Y=X+ + +1 Forcomplexliteralconstantsweneedtospecif ya(realpart,imaginarypart) :25+4:1iwedoZ=( , )Logicalconstantscantakeoneoftwovalues,w rittenasQ=.
7 ,characterliteralconstantsaredelimitedby singleordoublequotesC='A'orC="A"Ifthedel imiterispartofthestring,theconventionist owriteittwiceinsidethestring,forexampleC ='O"Malley'12c AdrianSandu, ::a,blogical::a<relationaloperator>bF77 > >= <= < (. ). ( ) ::a,blogical::[a]<logicaloperator> ( ,elseF). ( ,elseT). , ,ifoperandshavedi ::a,blogical::q1,q2q1=(. ).AND.( ) (len= ),parameter::school="michigantech"c AdrianSandu, (2:4)"ich"school(:8)"michigan"school(9:) "tech"school(4)error(stringisscalar)scho ol(4:4)"h"(correctform) (len= ),parameter::&state="michigan",name="tec h"character(len=12)::schoolschool=state/ /name!produces"michigantech" nedmonadichighest (tightestbinding) ;=.monadic+; .dyadic+; .==.relationaloperators(. ).. ,.NEQV.(weakestbinding)user-de neddyadiclowestFormultiplesame-leveloper atorsevaluationisdonelefttoright(exceptf or ).Paranthesiscanaltertheorderofevaluatio n, erences, C6=A=(B C)orA=2 29;B=1:999999 2 30;C=1:999998 2 30;X=A+B C!
8 X=1;(over ow)Y=A+(B C)!Y= :NOT:A:AND:B:EQV:C:OR:D:AND:E:OR:x:GT:y: AND:y: (are\intrinsic"toFortran). AdrianSandu, :[hnamei:]IF(hlogicalexpri)THEN hthenblocki[ ELSEIF(hlogicalexpri)THEN[hnamei]helseif blocki ][ELSE[hnamei]helseblocki]ENDIF[hnamei] , ,theELSEIF-shlogicalexpriessionsareevalu atedsuccesively,untilthe ,theELSE branchistaken(ifpresent).IftheELSE branchisnotpresentthecontrolistransferre dtothe (Discusscontrol owdiagramwithrombsandrectangles)if( )thenprint*,"i>17!"endifif( )thenprint*,"i>17!"elseprint*,"i<=17!"endifif( )thenprint*,"i>17!"elseif( )thenprint*,"i=17!"c AdrianSandu, ( )thenprint*,"i=16!"elseprint*,"i<16!" ::a,b,c!coe ::d!determinantreal::x1,x2!solutions,ifr eal(casesI,II)real::xre,xim!realandimagi narypartsofsolutions(caseIII)!readinthec oe cientsprint ,' .a,b,c:'read ,a,b,cd=b 2 a c!checkthecasesandtreatthemseperateif( )thenx1=( b SQRT(d))/( a)x2=( b+SQRT(d))/( a)print ,' :',&'x1=',x1,'x2=',x2elseif( )thenx1= b/( a)print ,' :',&'x1=x2=',x1else!
9 D<0xre= b/( a)xim=SQRT( d)/( a)print ,' conjugateroots:',&xre,'+/ ',xim,'i'endifendprogramquadraticeqn1 Exampleofcomplexnumbersuse:solvingaquadraticequation, ::a,b,ccomplex::d,x1,x2,sd!readinthecoe cientsprint ,'Pleasegivea,b,c:'read ,a,b,c!computediscriminantd=b 2 4 a c!sqrt(d):sincediscomplex,sqrtiscomplexsd=SQRT(d)!computeroots:x1=( b+sd)/( a)x2=( b sd)/( a)print ,'Rootsare'print ,'X1=',x116c AdrianSandu, ,'X2=', :DOhDOvari=hnexpr1i;hnexpr2i[;hnexpr3i] ,hnexpr2iand,ifpresent, ,hnexpr3iisassumedtohavethedefaultvalue= ,DOvar #it=max bhnexpr2i hnexpr1ihnexpr3ihnexpr3ic;0 Notethatboththenumberofiterations# #it> ,theiterationcounterisdecrementedby1#it #it 1andtheDOvariable(DOvar)ismodi edbyaddingthestrideDOvar DOvar+hnexpr3iTheiterationcontinuesif#it >0, ,attheendoftheiterations,DOvarmightassum eavaluedi (andresultsinacompilationerror).Forexamp le, ,9print ,ienddowillexecutetheloopexactly11times, andwillproducetheoutput1;2;3; ,9,2print ,ienddoc AdrianSandu, ;3;5; ,thecodedoi=9,1, 2print ,ienddowillproducetheoutput9;7;5 ,1,1print ,ienddowillproducenooutputsinceinitially #it= ,theloopdoi=1,9, 1print ,ienddonnwillproducenooutputsinceinitial ly#it=max( 8;0)= nishestheinnermostloop;however,withnamed doloops,itcanexittheindicatedloop, ,CYCLE outercyclesbacktotheouterloop, :doi=1,9inner:doj=i,9print*,"before:",i, jif( )cycleouter!
10 Gotoouter:doprint*,"before:",i,jif( )exitouter!gotoouter:doprint*,"after:",i , :FahrenheittoCelsiusWriteaprogramthatcon vertsthetemperaturefromFahrenheitdegrees toCelsiusdegrees(centigrades). ,andiftheresultiswrong, ::n! AdrianSandu, ::f,c! ,Cinteger::i!loopcounterprint ,' 'read ,ndoi=1,nprint ,' ',i,'='read ,fc= (f 32)print ,f,'Fis',c,'C' ; ; ,andlogicalexpressions; ;thisintroducesaDOloopandintegervariable s; rstreadall5radiiandthencomputeall5areas; (N=5) (keyboard/console)read ,Rprint ,Vprint ,'R=',Rorprint*,"R=", lesInFortran, lesaredesignatedbyunitnumber, ,standarderror, ned ned ned les,weneedtoOPEN them(thisissomehowsimilartovariabledecla ration).Forexample,thestatementopen(unit =10,file=' ',action='READ')c AdrianSandu, lenamed' ';themodedeclarationstatesthatthisisanin put(read-only) le;thestatementwillallocateunitnumber10t othe le' ';fromnowon,allREAD(10,*)willreadindataf romthis (unit=11,file=' ',action='WRITE')nendftabulargwillopenth e lenamed' ';ifnotpresent,willcreateone;themodedecl arationstatesthatthisisanoutput(writeabl e) le;thestatementwillallocateunitnumber11t othe le' ';fromnowon,allWRITE(11,*)willwritedatai ntothis (unlessexplicitformatisused).