Example: biology

Introductory Fortran Programming - Delaware Physics

MotivationIntroductoryFortranProgramming Gunnar WollanDepartmentofGeosciencesUniversity ofOslo,N-0315 Oslo,NorwaySpring2005 Gunnar WollanIntroductoryFortranProgrammingMoti vationMotivation1 MotivationGunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95 ContentsGentleintroductiontoFortran77and 95programmingFileI/OArraysandloopsDetail edexplanationofmodulesComputationale ciencyaspectsUsingmodulesasobjectsThepro miseofFortran2003 Gunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95 RequiredbackgroundProgrammingexperiencew itheitherC++,Javaor MatlabInterestinnumericalcomputingusingF ortranInterestinwritinge cientprogramsutilizinglow-leveldetailsof thecomputerGunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95 AboutlearningFortranFortranisa lesscomplicatedlanguagethanC++andJavaEve nsoit takestimetomastertheadvanceddetailsofFor tran95At least6 monthstoa year workingwithFortran95beforeyouarefamiliar withthedetailsFourdayscanonlygetyoustart edYouneedtouseFortran95inyourownprojects tomasterthelanguageFortran77codeisnotthe maintopichere,butyouneedtohavesomeknowle dgeofitGunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95 TeachingphilosophyIntensivecourseLecture s9 - 12 Hands-ontraining13- 16 LearnformdissectingexamplesGetintouchwit hthedirty workGetsomeoverviewofadvancestopicsFocus onprinciplesandg

Motivation Introductory Fortran Programming Gunnar Wollan Department of Geosciences University of Oslo, N-0315 Oslo, Norway Spring 2005 Gunnar Wollan Introductory Fortran Programming

Tags:

  Introductory, Fortran, Introductory fortran

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Transcription of Introductory Fortran Programming - Delaware Physics

1 MotivationIntroductoryFortranProgramming Gunnar WollanDepartmentofGeosciencesUniversity ofOslo,N-0315 Oslo,NorwaySpring2005 Gunnar WollanIntroductoryFortranProgrammingMoti vationMotivation1 MotivationGunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95 ContentsGentleintroductiontoFortran77and 95programmingFileI/OArraysandloopsDetail edexplanationofmodulesComputationale ciencyaspectsUsingmodulesasobjectsThepro miseofFortran2003 Gunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95 RequiredbackgroundProgrammingexperiencew itheitherC++,Javaor MatlabInterestinnumericalcomputingusingF ortranInterestinwritinge cientprogramsutilizinglow-leveldetailsof thecomputerGunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95 AboutlearningFortranFortranisa lesscomplicatedlanguagethanC++andJavaEve nsoit takestimetomastertheadvanceddetailsofFor tran95At least6 monthstoa year workingwithFortran95beforeyouarefamiliar withthedetailsFourdayscanonlygetyoustart edYouneedtouseFortran95inyourownprojects tomasterthelanguageFortran77codeisnotthe maintopichere,butyouneedtohavesomeknowle dgeofitGunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95 TeachingphilosophyIntensivecourseLecture s9 - 12 Hands-ontraining13- 16 LearnformdissectingexamplesGetintouchwit hthedirty workGetsomeoverviewofadvancestopicsFocus onprinciplesandgenericstrategiesContinue dlearningonindividualbasisThiscoursejust getyoustarted- usetextbooks.

2 Referencemanualsandsoftwareexamplesfromt heinternetfor furtherworkwithprojectsGunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95recommendedatti dudeDiveintoexecutableexamplesDon'ttryto understandeverythingTrytoadaptexamplesto newproblemsLookuptechnicaldetailsinmanua ls/textbooksLearnondemandKeepa coolheadMake yourprogramsmallandfast- thenyoursoftwarelongwilllastGunnar WollanIntroductoryFortranProgrammingMoti vationAboutFortran77and95 AboutFortran77and952 AboutFortran77and95 Gunnar WollanIntroductoryFortranProgrammingAbou tFortran77and95 IntrotoFortran77programmingFortran77 Intotheearly/middleoftheninetiesFortran7 7wasthedominatinglanguagefor numbercrunchingIt'spredecessor FortranIVwasreplacedby manyprocedurallanguagesFortranhasa failrysimplesyntaxFortranisgood for onlyonething,NUMBERCRUNCHINGG unnar WollanIntroductoryFortranProgrammingAbou tFortran77and95 IntrotoFortran77programmingFortran95 Fortran95extendsFortran77withNicersyntax ,freeformatinsteadof xedformatUserde neddatatypesusingtheTYPE declaraionModulescontainingdatade nitionsandproceduredeclarationsNoimplici tvariabledeclaretions,avoidingtypingerro rsFortran77is a subsetoffortran95 Gunnar WollanIntroductoryFortranProgrammingAbou tFortran77and95 IntrotoFortran77programmingFortranversus otherlanguagesCis lowlevelandclosetothemachine.

3 Butcanbe error proneC++isa supersetofCandmorereliableJavais simplerandmorereliablethanC++Pythonis morehigh-levelthanJavaGunnar WollanIntroductoryFortranProgrammingAbou tFortran77and95 IntrotoFortran77programmingSpeedofFortra nversusotherlanguagesFortran77isregarded asveryfastCyieldslightlyslowercodeC++and fortran95areslowerthanFortran77 Javais muchslowerGunnar WollanIntroductoryFortranProgrammingAbou tFortran77and95 IntrotoFortran77programmingSomeguideline sFortran77givesveryfastprograms,buttheso urcecodeislessreadableandmoreerror proneduetoimplicitdeclarationsUseFortran 95for yourmainprogramandFortran77functionswher espeediscriticalSometimesthebestsolution is a combinationoflanguages, ,PythonandC++Usethelanguagebestsuitedfor yourproblemGunnar WollanIntroductoryFortranProgrammingAbou tFortran77and95 IntrotoFortran77programmingIntrotoFortra n77programming3 IntrotoFortran77programmingGunnar WollanIntroductoryFortranProgrammingIntr otoFortran77programmingIntrotoFortran95p rogrammingOur rstFortran77programGoal.

4 Make a programwritingthetext\HelloWorld"Impleme ntationWithoutdeclaringa stringWithstringdeclarationGunnar WollanIntroductoryFortranProgrammingIntr otoFortran77programmingIntrotoFortran95p rogrammingWithoutdeclaringa stringvariableC234567 PROGRAMhw1 WRITE(*,*)'HelloWorld'END PROGRAMhw1 Gunnar WollanIntroductoryFortranProgrammingIntr otoFortran77programmingIntrotoFortran95p rogrammingWithdeclaringa stringvariableC234567 PROGRAMhw1 CHARACTER*11strWRITE(*,*)strEND PROGRAMhw1 Gunnar WollanIntroductoryFortranProgrammingIntr otoFortran77programmingIntrotoFortran95p rogrammingSomecommentstothe\HelloWorld"p rogramFortran77uses xedformatThesourcecodeisdividedintoposit ionsonthelineThisis a heritagefromtheolddayswhencommunicationw iththecomputerwasby punchedcardsAcharacterinthe rstcolumnidenti estothecompilerthattherestofthelineisa commentThecoumns2 to5 isfor jumplabelsandformatspeci ersColumn6 is for continuationofthepreviouslineThecolumn7 to72isfor thesourcecodeColumn73to80isfor commentsGunnar WollanIntroductoryFortranProgrammingIntr otoFortran77programmingIntrotoFortran95p rogrammingIntrotoFortran95programming4 IntrotoFortran95programmingGunnar WollanIntroductoryFortranProgrammingIntr otoFortran95programmingCompilingandlinki ngFortranprogramsScienti cHelloWorldinFortran95 Usage.

5 ,World!sin( )= rstcommand-lineargumentina oating-pointvariable2 Callthesinefunction3 Writea combinationoftextandnumberstothescreenGu nnar WollanIntroductoryFortranProgrammingIntr otoFortran95programmingCompilingandlinki ngFortranprogramsThecodePROGRAMhw1 IMPLICITNONEDOUBLEPRECISION:: r, sCHARACTER(LEN=80):: argv! InputargumentCALL getarg(1,argv)! A C-functionr = a2d(argv)! Our own asciito! doubles = SIN(r)! The intrinsicSINE! functionPRINT*, 'HelloWordsin(',r,')=',sEND PROGRAMhw1 Gunnar WollanIntroductoryFortranProgrammingIntr otoFortran95programmingCompilingandlinki ngFortranprogramsDissection(1)Contraryto C++thecompilerdoesnotneedtoseadeclaratio nofsubroutinesandintrinsicfunctionsOnlye xternalfunctionsmustbe declaredCommentsinFortran95arethe! ona lineThecodeisfreeformatunlike Fortran77 Gunnar WollanIntroductoryFortranProgrammingIntr otoFortran95programmingCompilingandlinki ngFortranprogramsDissection(2)Allprogram swritteninFortranbeginswiththestatementP ROGRAM programnameandendswiththestatementENDwit htheoptionalPROGRAM programnameUnlike C++andotherprogramminglanguageFortranhas nobuiltintransferofcommandlineargumentsA calltoa C-functiongetarg(n,argv)transfersthen'th argumenttothecharacter-stringvariablearg vGunnar WollanIntroductoryFortranProgrammingIntr otoFortran95programmingCompilingandlinki ngFortranprogramsDissection(2)Floatingpo intvariablesinFortran1 REAL:singleprecision2 DOUBLEPRECISION:doubleprecisiona2d:youro wnasciistringtodoublefunction,Fortranhas nointrinsicfunctionsofthiskindincontrast toC/C++soyouhavetowritethisoneyourselfAu tomatictype conversion.

6 DOUBLEPRECISION=REALTheSIN()functionisan intrinsicfunctionanddoesnotneeda speci cdeclarationGunnar WollanIntroductoryFortranProgrammingIntr otoFortran95programmingCompilingandlinki ngFortranprogramsAninteractiveversionLet usasktheuserfor therealnumberinsteadofreadingitfromtheco mmandlineWRITE(*.FMT='(A)',ADVANCE='NO') 'Givea realnumber:'READ(*,*)rs = SIN(r)! WollanIntroductoryFortranProgrammingIntr otoFortran95programmingCompilingandlinki ngFortranprogramsScienti cHelloWorldinFortran77C234567 PROGRAMhw1 REAL*8r,sCHARACTER*80argvCALL getarg(1,argv)r = a2d(argv)s = SIN(r)WRITE(*,*)'HelloWorld!sin(',r')=', sEND PROGRAMhw1 Gunnar WollanIntroductoryFortranProgrammingIntr otoFortran95programmingCompilingandlinki ngFortranprogramsDi erencesfromtheFortran95versionFortran77u sesREAL*8insteadofDOUBLEPRECISIONF ortran77lacksIMPLICITNONE directiveAdoubleprecisionvariablehastobe declaredinFortran77sincedefaultrealnumbe rsaresingleprecisionGunnar WollanIntroductoryFortranProgrammingIntr otoFortran95programmingCompilingandlinki ngFortranprogramsCompilingandlinkingFort ranprograms5 CompilingandlinkingFortran95programsGunn ar WollanIntroductoryFortranProgrammingComp ilingandlinkingFortran95programsManipula tedata lesHowtocompileandlink(Fortran95)Onestep (compilingandliking):unix> steps:unix> #Compile, > #LinkAlinuxsystemwithIntelFortranCompile r:linux> WollanIntroductoryFortranProgrammingComp ilingandlinkingFortran95programsManipula tedata lesUsingthemake utility tocompilea programWhatisthemake utility?

7 Themake utility readsa lecontainingthename(s)ofthe le(s)tobe compiledtogehterwiththenameoftheexecutab leprogramThemake leis eithercalled\make le"or \Make le"asdefaultInvokingthemake utiltity:unix-linux>makeGunnar WollanIntroductoryFortranProgrammingComp ilingandlinkingFortran95programsManipula tedata lesAshortexampleofa make leFC= f90$(shellls *. )SRC=$(shellcat ./srclist)OBJECTS=$(SRC:.f90=.o)prog: $(OBJECTS)$(FC)-o $@ $(OBJECTS)%.o : %.f90$(FC)-c $?Gunnar WollanIntroductoryFortranProgrammingComp ilingandlinkingFortran95programsManipula tedata lesRollingyourownmake scriptThemainfeatureofa make leis tochecktimestampsin lesandonlyrecompiletherequired lesSincethesyntaxofa make leiskindofawkwardandeach avourofunixhasitsownspecialitiesyoucanma ke yourownscriptdoingalmostthesameGunnar WollanIntroductoryFortranProgrammingComp ilingandlinkingFortran95programsManipula tedata (1)#!/bin/shif [ ! -n ``$F90_COMPILER'']; thencase`uname-s` inLinux)F90_COMPILER=ifortF90_OPTIONS='' -Wall-O3'';;*)F90_COMPILER=f90F90_OPTION S=''-Wall-O3''esacfiGunnar WollanIntroductoryFortranProgrammingComp ilingandlinkingFortran95programsManipula tedata (2)files=`/bin/ls*.

8 F90`for filein files;dostem=`echo$file| sed 's/\.f90//'`echo$F90_COMPILER$F90_OPTION S-I. -o $stem$file$F90_COMPILER$F90_OPTIONS-I. -o $stem$filels -s stemdoneGunnar WollanIntroductoryFortranProgrammingComp ilingandlinkingFortran95programsManipula tedata lesHowtocompileandlink(Fortran77)Eitheru sethef90compileror if presentthef77compilerRememeberthatFortra n77is s subsetofFortran95 Anexample:f90 -o -o WollanIntroductoryFortranProgrammingComp ilingandlinkingFortran95programsManipula tedata lesHowtocompileandlinkingeneralWe compilea setofprogramsinFortranandC++Compileeachs etof leswiththerightcompiler:unix$>$f90 -O3 -c *.f90unix$>$g++ -O3 -c *.cppThenlink:unix$>$f90 -o exec\_file-L/some/libdir\\-L/other/libdi r*.o -lmylib-lyourlibLibrarytype:lib*.a:stati c;lib*.so:dynamicGunnar WollanIntroductoryFortranProgrammingComp ilingandlinkingFortran95programsManipula tedata lesManipulatedata les6 Manipulatedata lesGunnar WollanIntroductoryFortranProgrammingMani pulatedata lesFilehandlinginFortranExample:Datatran sformationSupposewe havea wanttotransformthey datausingsomemathematicalfunctionf(y)Goa l:writea Fortran95programthatreadsthe le,transformsthey dataandwritethenewxy-datatoa new leGunnar WollanIntroductoryFortranProgrammingMani pulatedata lesFilehandlinginFortranProgramstructure 1 Readthenamesofinputandoutput lesascommand-linearguments2 Printerror/usagemessageif lessthantwo command-lineargumentsaregiven3 Openthe les4 Whilemoredatainthe le.

9 Readx andy fromtheinput lesety=myfunc(y)writex andy totheoutput le5 Closethe lesGunnar WollanIntroductoryFortranProgrammingMani pulatedata lesFilehandlinginFortranThefortran95code (1)FUNCTION myfunc(y)RESULT(r)IMPLICITNONEDOUBLEPREC ISION,INTENT(IN):: yDOUBLEPRECISION:: rIF(y>=0.)THENr = y** *EXP(-y)ELSEr = IFEND FUNCTION myfuncGunnar WollanIntroductoryFortranProgrammingMani pulatedata lesFilehandlinginFortranThefortran95code (2)PROGRAM dtransIMPLICITNONEINTEGER:: argc,rstatDOUBLEPRECISION:: x, yCHARACTER(LEN=80):: infilename,outfilenameINTEGER,PARAMETER: : ilun= 10 INTEGER,PARAMETER:: olun= 11 INTEGER,EXTERNAL:: iargcargc= iargc()IF (argc< 2) THENPRINT*, 'Usage:dtransinfileoutfile'STOPEND IFCALL getarg(1,infilename)CALL getarg(2,outfilename)Gunnar WollanIntroductoryFortranProgrammingMani pulatedata lesFilehandlinginFortranThefortran95code (3)OPEN(UNIT=ilun,FILE=infilename,FORM=' FORMATTED',&IOSTAT=rstat)OPEN(UNIT=olun, FILE=outfilename,FORM='FORMATTED',&IOSTA T=rstat)rstat= 0DO WHILE(rstat== 0)READ(UNIT=ilun,FMT='( ,X, )',IOSTAT=rstat)&x, yIF(rstat/= 0) THENCLOSE(ilun)CLOSE(olun)STOPEND IFy = myfunc(y)WRITE(UNIT=olun,FMT='( ,X, )',IOSTAT=rstat)&x, yEND DOEND PROGRAM dtransGunnar WollanIntroductoryFortranProgrammingMani pulatedata lesFilehandlinginFortranFilehandlinginFo rtran7 FilehandlinginFortranGunnar WollanIntroductoryFortranProgrammingFile handlinginFortranArraysandloopsFortran leopeningOpena lefor readingOPEN(UNIT=ilun,FORM='FORMATTED',I OSTAT=rstat)Opena lefor writingOPEN(UNIT=ilun,FORM='FORMATTED',I OSTAT=rstat)

10 Openfor appendingdataOPEN(UNIT=ilun,FORM='FORMAT TED',&POSITION='APPEND',IOSTAT=rstat)Gun nar WollanIntroductoryFortranProgrammingFile handlinginFortranArraysandloopsFortran lereadingandwritingReada doubleprecisionnumberREAD(UNIT=ilun,FMT= '( )',IOSTAT=rstat) xTestif thereadingwassuccessfulIF(rstat/= 0) STOPW ritea doubleprecisionnumberWRITE(UNIT=olun,FMT ='( )',IOSTAT=rstat) xGunnar WollanIntroductoryFortranProgrammingFile handlinginFortranArraysandloopsFormatted outputTheformattedoutputinFortranisselec tedviatheFORMATofFMTstatementInfortran77 theFORMAT statementisusedC234567100 FORMAT( )WRITE(*,100)xInFortran95theFMTstatement isusedWRITE(*,FMT='( )')xGunnar WollanIntroductoryFortranProgrammingFile handlinginFortranArraysandloopsAconvenie ntway offormattinginFortran95(1)Insteadofwriti ngtheformatintheFMTstatementwe canputit ina stringvariableCHARACTER(LEN=7):: fmt_stringfmt_string= '( )'WRITE(*,FMT=fmt_string)xGunnar WollanIntroductoryFortranProgrammingFile handlinginFortranArraysandloopsAconvenie ntway offormattinginFortran95(2)We canusea setofsuchformatstringsCHARACTER(LEN=7),D IMENSION(3) :: fmt_stringfmt_string(1)= '( )'fmt_string(2)= '(2I4)'fmt_string(3)= '( )'WRITE(*,FMT=fmt_string(1)) xGunnar WollanIntroductoryFortranProgrammingFile handlinginFortranArraysandloopsUnformatt edI/OinFortranMoreoftenthannotwe usehugeamountofdatabothforinputandoutput Usingformatteddataincreaseboththe lesizeandthetimespentreadingandwritingda tafrom/to lesWe thereforeuseunformatteddatainthesecasesG unna


Related search queries