Fortran TutorialDepartment of Physics.docx

上传人:b****8 文档编号:12543613 上传时间:2023-06-06 格式:DOCX 页数:44 大小:37.93KB
下载 相关 举报
Fortran TutorialDepartment of Physics.docx_第1页
第1页 / 共44页
Fortran TutorialDepartment of Physics.docx_第2页
第2页 / 共44页
Fortran TutorialDepartment of Physics.docx_第3页
第3页 / 共44页
Fortran TutorialDepartment of Physics.docx_第4页
第4页 / 共44页
Fortran TutorialDepartment of Physics.docx_第5页
第5页 / 共44页
Fortran TutorialDepartment of Physics.docx_第6页
第6页 / 共44页
Fortran TutorialDepartment of Physics.docx_第7页
第7页 / 共44页
Fortran TutorialDepartment of Physics.docx_第8页
第8页 / 共44页
Fortran TutorialDepartment of Physics.docx_第9页
第9页 / 共44页
Fortran TutorialDepartment of Physics.docx_第10页
第10页 / 共44页
Fortran TutorialDepartment of Physics.docx_第11页
第11页 / 共44页
Fortran TutorialDepartment of Physics.docx_第12页
第12页 / 共44页
Fortran TutorialDepartment of Physics.docx_第13页
第13页 / 共44页
Fortran TutorialDepartment of Physics.docx_第14页
第14页 / 共44页
Fortran TutorialDepartment of Physics.docx_第15页
第15页 / 共44页
Fortran TutorialDepartment of Physics.docx_第16页
第16页 / 共44页
Fortran TutorialDepartment of Physics.docx_第17页
第17页 / 共44页
Fortran TutorialDepartment of Physics.docx_第18页
第18页 / 共44页
Fortran TutorialDepartment of Physics.docx_第19页
第19页 / 共44页
Fortran TutorialDepartment of Physics.docx_第20页
第20页 / 共44页
亲,该文档总共44页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

Fortran TutorialDepartment of Physics.docx

《Fortran TutorialDepartment of Physics.docx》由会员分享,可在线阅读,更多相关《Fortran TutorialDepartment of Physics.docx(44页珍藏版)》请在冰点文库上搜索。

Fortran TutorialDepartment of Physics.docx

FortranTutorialDepartmentofPhysics

RichardKass

Winter2004

APhysics416FortranTutorial

(basedontheinformationat:

http:

//macams1.bo.infn.it/tutorial/)

1.WhatisFortran?

2.Fortranbasics

3.Variables,declarations,andtypes

4.Expressionsandassignment

5.Logicalexpressions

6.Theifstatements

7.Loops

8.Arrays

9.Subprograms

10.RandomnumbersandMonteCarlosimulations

11.Simpleinputandoutput

12.Formatstatements

13.FileI/O

14.Commonblocks

15.dataandblockdata

16.Debugging

17.RunningFortranonthePhysicsDepartment’sVAX(OHSTPY)computer

18.AsampleFortranprogramforLab1

1.WhatisFortran?

Fortranisageneralpurposeprogramminglanguage,mainlyintendedformathematicalcomputationsinscienceapplications(e.g.physics).FortranisanacronymforFORmulaTRANslation,andwasoriginallycapitalizedasFORTRAN.However,followingthecurrenttrendtoonlycapitalizethefirstletterinacronyms,wewillcallitFortran.Fortranwasthefirsthigh-levelprogramminglanguage.TheworkonFortranstartedinthe1950'satIBMandtherehavebeenmanyversionssince.Byconvention,aFortranversionisdenotedbythelasttwodigitsoftheyearthestandardwasproposed.ThuswehaveFortran66,Fortran77andFortran90(95).

ThemostcommonFortranversiontodayisstillFortran77,althoughFortran90isgrowinginpopularity.Fortran95isarevisedversionofFortran90whichisexpectedtobeapprovedbyANSIsoon(1996).TherearealsoseveralversionsofFortranaimedatparallelcomputers.ThemostimportantoneisHighPerformanceFortran(HPF),whichisade-factostandard.

UsersshouldbeawarethatmostFortran77compilersallowasupersetofFortran77,i.e.theyallownon-standardextensions.InthistutorialwewillemphasizestandardANSIFortran77.

WhylearnFortran?

Fortranisthedominantprogramminglanguageusedinscientificapplications.Itisthereforeimportantforphysics(orengineering)studentstobeabletoreadandmodifyFortrancode.Fromtimetotime,so-calledexpertspredictthatFortranwillrapidlyfadeinpopularityandsoonbecomeextinct.ThismayactuallyhappenasC(orC++)israpidlygrowinginpopularity.However,previouspredictionsofthedownfallofFortranhavealwaysbeenwrong.Fortranisthemostenduringcomputerprogramminglanguageinhistory.OneofthemainreasonsFortranhassurvivedandwillsurviveissoftwareinertia.Onceacompanyhasspentmanypeople-yearsandperhapsmillionsofdollarsonasoftwareproduct,itisunlikelytotrytotranslatethesoftwaretoadifferentlanguage.Reliablesoftwaretranslationisaverydifficulttaskandthere’s40yearsofFortrancodetoreplace!

Portability

AmajoradvantageFortranhasisthatitisstandardizedbyANSI(AmericanNationalStandardsInstitute)andISO(InternationalStandardsOrganization).Consequently,ifyourprogramiswritteninANSIFortran77thenitwillrunonanycomputerthathasaFortran77compiler.Thus,Fortranprogramsareportableacrosscomputerplatforms

2.Fortran77Basics

AFortranprogramisjustasequenceoflinesoftext.ThetexthastofollowacertainsyntaxtobeavalidFortranprogram.Westartbylookingatasimpleexamplewherewecalculatetheareaofacircle:

programcircle

realr,area

cThisprogramreadsarealnumberrandprints

ctheareaofacirclewithradiusr.

write(*,*)'Giveradiusr:

'

read(*,*)r

area=3.14159*r*r

write(*,*)'Area=',area

stop

end

Thelinesthatbeginwitha"c"arecommentsandhavenopurposeotherthantomaketheprogrammorereadableforhumans.Originally,allFortranprogramshadtobewritteninallupper-caseletters.Mostpeoplenowwritelower-casesincethisismorelegible.

Programorganization

AFortranprogramgenerallyconsistsofamainprogram(ordriver)andpossiblyseveralsubprograms(orproceduresorsubroutines).Fornowwewillassumeallthestatementsareinthemainprogram;subprogramswillbetreatedlater.Thestructureofamainprogramis:

programname

declarations

statements

stop

end

Inthistutorial,wordsthatareinitalicsshouldnotbetakenasliteraltext,butratherasagenericdescription.Thestopstatementisoptionalandmayseemsuperfluoussincetheprogramwillstopwhenitreachestheendanywaybutitisrecommendedtoalwaysterminateaprogramwiththestopstatementtoemphasizethattheexecutionflowstopsthere.

Columnpositionrules

Fortran77isnotafree-formatlanguage,buthasaverystrictsetofrulesforhowthesourcecodeshouldbeformatted.Themostimportantrulesarethecolumnpositionrules:

Col.1:

Blank,ora"c"or"*"forcomments

Col.2-5:

Statementlabel(optional)

Col.6:

Continuationofpreviousline(optional)

Col.7-72:

Statements

Col.73-80:

Sequencenumber(optional,rarelyusedtoday)

MostlinesinaFortran77programstartswith6blanksandendsbeforecolumn72,i.e.onlythestatementfieldisused.NotethatFortran90allowsfreeformat.

Comments

Alinethatbeginswiththeletter"c"oranasteriskinthefirstcolumnisacomment.Commentsmayappearanywhereintheprogram.Well-writtencommentsarecrucialtoprogramreadability.CommercialFortrancodesoftencontainabout50%comments.YoumayalsoencounterFortranprogramsthatusetheexclamationmark(!

)forcomments.Thisishighlynon-standardinFortran77,butisallowedinFortran90.Theexclamationmarkmayappearanywhereonaline(exceptinpositions2-6).

Continuation

Occasionally,astatementdoesnotfitintoonesingleline.Onecanthenbreakthestatementintotwoormorelines,andusethecontinuationmarkinposition6.Example:

c23456789(Thisdemonstratescolumnposition!

cThenextstatementgoesovertwophysicallines

area=3.14159265358979

+*r*r

Anycharactercanbeusedinsteadoftheplussignasacontinuationcharacter.Itisconsideredgoodprogrammingstyletouseeithertheplussign,anampersand,ornumbers(2forthesecondline,3forthethird,andsoon).

Blankspaces

BlankspacesareignoredinFortran77.SoifyouremoveallblanksinaFortran77program,theprogramisstillsyntacticallycorrectbutalmostunreadableforhumans.

3.Variables,types,anddeclarations

Variablenames

VariablenamesinFortranconsistof1-6characterschosenfromthelettersa-zandthedigits0-9.Thefirstcharactermustbealetter.(Note:

Fortran90allowsvariablenamesofarbitrarylength).Fortran77doesnotdistinguishbetweenupperandlowercase,infact,itassumesallinputisuppercase.However,nearlyallFortran77compilerswillacceptlowercase.IfyoushouldeverencounteraFortran77compilerthatinsistsonuppercaseitisusuallyeasytoconvertthesourcecodetoalluppercase.

Typesanddeclarations

Everyvariableshouldbedefinedinadeclaration.Thisestablishesthetypeofthevariable.Themostcommondeclarationsare:

integerlistofvariables

reallistofvariables

doubleprecisionlistofvariables

complexlistofvariables

logicallistofvariables

characterlistofvariables

Thelistofvariablesshouldconsistofvariablenamesseparatedbycommas.Eachvariableshouldbedeclaredexactlyonce.Ifavariableisundeclared,Fortran77usesasetofimplicitrulestoestablishthetype.Thismeansallvariablesstartingwiththelettersi-nareintegersandallothersarereal.ManyoldFortran77programsusestheseimplicitrules,butyoushouldnot!

Theprobabilityoferrorsinyourprogramgrowsdramaticallyifyoudonotconsistentlydeclareyourvariables.

Integersandfloatingpointvariables

Fortran77hasonlyonetypeforintegervariables.Integersareusuallystoredas32bits(4bytes)variables.Therefore,allintegervariablesshouldtakeonvaluesintherange[-m,m]wheremisapproximately2*10^9.

Fortran77hastwodifferenttypesforfloatingpointvariables,calledrealanddoubleprecision.Whilerealisoftenadequate,somenumericalcalculationsneedveryhighprecisionanddoubleprecisionshouldbeused.Usuallyarealisa4bytevariableandthedoubleprecisionis8bytes,butthisismachinedependent.Somenon-standardFortranversionsusethesyntaxreal*8todenote8bytefloatingpointvariables.

Theparameterstatement

Someconstantsappearmanytimesinaprogram.Itisthenoftendesirabletodefinethemonlyonce,inthebeginningoftheprogram.Thisiswhattheparameterstatementisfor.Italsomakesprogramsmorereadable.Forexample,thecircleareaprogramshouldhavebeenwrittenlikethis:

programcircle

realr,area,pi

parameter(pi=3.14159)

cThisprogramreadsarealnumberrandprints

ctheareaofacirclewithradiusr.

write(*,*)'Giveradiusr:

'

read(*,*)r

area=pi*r*r

write(*,*)'Area=',area

stop

end

Thesyntaxoftheparameterstatementis

parameter(name=constant,...,name=constant)

Therulesfortheparameterstatementare:

⎽The"variable"definedintheparameterstatementisnotavariablebutratheraconstantwhosevaluecanneverchange

⎽A"variable"canappearinatmostoneparameterstatement

⎽Theparameterstatement(s)mustcomebeforethefirstexecutablestatement

Somegoodreasonstousetheparameterstatementare:

⎽ithelpsreducethenumberoftypos

⎽itiseasytochangeaconstantthatappearsmanytimesinaprogram

4.Expressionsandassignment

Constants

Thesimplestformofanexpressionisaconstant.Thereare6typesofconstants,correspondingtothe6datatypes.Herearesomeintegerconstants:

1

0

-100

32767

+15

Thenwehaverealconstants:

1.0

-0.25

2.0E6

3.333E-1

TheE-notationmeansthatyoushouldmultiplytheconstantby10raisedto

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 农林牧渔 > 林学

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2