1. Trang chủ
  2. » Công Nghệ Thông Tin

introduce to programming using fortran 95

45 178 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 45
Dung lượng 420,99 KB

Nội dung

Copyright©JanetANicholson2011 1 fortrantutorial.com   IntroductiontoProgramming usingFORTRAN95  http://www.fortrantutorial.com/       Theseworksheetsaimtoprovideanintroductionto programming.ThelanguagechosenforthisisFORTRAN95.This isbecauseFORTRANisparticularlysuitableforscienceand engineering;itisalsoverywidelyavailable.  Theskillsyouacquireworkingthroughthesenotescanbe appliedtoanycomputinglanguage.Theconceptsyouwilllearn aresharedincommonwitheveryothercomputinglanguage.   Thisdocumentandalltheexamplesmaybefoundonlineat:  http://www.fortrantutorial.com/   ©JanetANicholson2011 Copyright©JanetANicholson2011 2 fortrantutorial.com 1 THEBASICS 3 1.1  AIMS 3 1.2 INSTALLFTN95PERSONALEDITION 3 1.3 YOURFIRSTPROGRAMMINGSESSION 3 1.4 PLATOAPROGRAMMINGE NVIRONMENT 3 1.5 RUNNINGYOURFIRSTFORTRAN95PROGRAM 4 1.6 PROGRAMSTRUCTURE 6 1.7 MOREONINPUTANDOUTPUT 6 1.8 MOREDATATYPES–INTEGERANDCHARACTER 8 1.9 SAVINGTHECONTENTSOFOUTPUTWINDOW 10 2 MAKINGDECISIONS 11 2.1 AIMS 11 2.2 ASSIGNMENT 11 2.3 ARITHMETIC 11 2.4 INTRINSICFUNCTIONS 12 2.5 MAKINGDECISIONS 13 2.6 PROGRAMSTYLE 14 2.7 MOREONDECISIONMAKING 14 2.8 OTHERLOGICALOPERATORS 14 2.9 MULTIPLECONDITIONS 15 2.10 THESIMPLEIFSTATEMENT 15 2.11 IMPORTANTNOTE–TESTINGFORZERO 16 3 LOOPS 17 3.1 AIMS 17 3.2 MIXINGVARIABLETYPES 17 3.3 THEDOLOOP 18 3.4 NESTEDDOLOOPS 19 3.5 USINGLOOPSTODOSUMMATION 20 4 USINGFILESANDEXTENDINGPRECISION 22 4.1 AIMS 22 4.2 READINGFROMFILES 22 4.3 WRITINGTOFILES 23 4.4 EXTENDINGTHEPRECISION 23 4.5 MAGNITUDELIMITATIONS 25 4.6 CONVERGENCE–EXITINGLOOPSONACONDITION 25 5 ARRAYSANDFORMATTEDI/O 27 5.1 AIMS 27 5.2 ARRAYS 2 7 5.3 ARRAYMAGIC 29 5.4 MULTIDIMENSIONALARRAYS 30 5.5 FORMATTINGYOUROUTPUT 31 5.5.1 IntegerSpecification 32 5.5.2 FloatingpointSpecification 32 5.5.3 ExponentialSpecification 32 5.5.4 CharacterSpecification 33 5.6 IMPLIEDDOLOOPTOWRITEARRAYS 33 6 SUBROUTINESANDFUNCTIONS 35 6.1 AIMS 35 6.2 REUSINGCODE–THESUBROUTINE 35 6.3 ARGUMENTSTOSUBROUTINES 36 6.4 USERDEFINEDFUNCTIONS 38 7 ADVANCEDTOPICS 40 7.1 AIMS 40 7.2 ARRAYFUNCTIONS 40 7.3 WRITINGREALPROGRAMSFLOWCHARTS 42 Copyright©JanetANicholson2011 3 fortrantutorial.com  1 TheBasics 1.1 Aims Bytheendofthisworksheet,youwillbeableto:  CreateandrunaFORTRAN95program  Understandbasicprogramstructure  Starttodealwithprogrammingerrors  Starttounderstandreal,integerandcharactervariabletypes.  SaveacopyofyouroutputinWord.  1.2 InstallFTN95PersonalEdition  SearchforSilverfrostFTN5personaleditionorclickthislink http://www.silverfrost.com/32/ftn95/ftn95_personal_edition.aspx .  Downloadandinstallthesoftwareacceptingallthedefaults. 1.3 Yourfirstprogrammingsession   LocateanddoubleclickthePlato icon  ClickFile,New  SelectFreeFormatFortranFile  ClickFile,SaveAs  Createadirectorycalledfortranprogramsandopenit  Typefirst.f95  1.4 Platoaprogrammingenvironment  Copyright©JanetANicholson2011 4 fortrantutorial.com Platoisa"programmingenvironment".WithinPlato,youcancreateandeditprogramsandgetthem torun.Plato'seditorisspecial–itunderstandsthesyntaxofvariousprogramminglanguages.Wetell Platowhichlanguageweareusingwhenwecreateouremptyfileandsaveitwitha.f95(FO RTRAN 95)extension.Providedyouhavegivenyourfiletheappropriateextension,Plato'seditorwillbeable tocheckthesyntaxoftheprogram,highlightingthevariouskeywordsthatitknowsaboutusinga colourcodetodistinguishbetweenthevariouselementsofthelanguage. Alwaysensurethatyourprogramfileshavea.f95extension 1.5 RunningyourfirstFORTRAN95Program   Exercise1.1  Typeinthefollowingexactlyasshown:  !My first program program first print *,'This is my first program' end program first  Copyright©JanetANicholson2011 5 fortrantutorial.com    Clicktheblack,(theExecutebutton).  PlatowillgetFTN95tocheckyourprogramforerrors.Ifitfindsanyproblems,itwillgiveyou thedetails.Ifyouhavetypedintheprogramexactlyasshownabove,anexecutablefilewill begenerated(first.exe).Platowillthenautomaticallygetthepro gramtostartexecuting.  Abannerwillappearforacoupleofsecondsandwillthendisappear(that"sthepricewe havetopayforusingthefreesoftware)  Ablackconsolewindowwillappear.  PressReturntoclosethewindow.DonotclicktheXatthetopri ghtofthewindow.  PlatocangetupsetifyoudonotpressReturntoclosethewindow,trythis…  Saveyourprogramfirst!  Runtheprogramagain(click)  ThistimeclicktheXatthetoprightofthewindowtoclos eit.  Makeupyourownmindaboutwhichisthebetterwaytoclosethiswindowinfuture!   Copyright©JanetANicholson2011 6 fortrantutorial.com 1.6 ProgramStructure Examinethefollowingshortprogram: program sum !a:nameofprogram  !an example of program structure !b:acomment  real :: answer,x,y !c:declarations print *, 'Enter two numbers' !d:output read *, x !e:input read *, y !e:input answer=x+y !f:arithmetic print *, 'The total is ', answer !g:output end program sum !h:endofprogram  Thereareanumberofgeneralpointshere:  Theprogramismadeupofanumberoflines.Eachlineiscalledastatement.  Eachstatementismadeupof  variablenamese.g.answer, x, y  operatorse.g.+,-etc  keywordse.g.read, print  Thestatementsareexecutedsequentially.  Let'sbreaktheprogramdown,linebyline: a) Thenameoftheprogram.Keepitreasonablyshortandmeaningful. b) Acommentexplainingthepurposeoftheprogram.Commentsareindicatedbyan exclamationmark.Alltexttotherightofanexclamationmarkisignoredbyth ecompiler. Programmersusecommentstohelpthemrememberhowaprogramworks.Useof appropriatecommentsinprogramsaidsunderstandingandisgoodpractice. c) Variablesanswer, x and y areusedtostorefloatingpointnumbers–weindicate thisbydeclaringthemasreal. d) print *,outputstoth escreen–theasteriskmeansusethedefaultnumberofdecimal placeswhenthenumberiswrittentothescreen. e) Wereadinformationfromthek eyboardandstorethevaluesin xandy. f) Dosomearithmeticandstoretheanswerinanswer. g) Outputtheresulttoth escreen h) Concludetheprogram   1.7 MoreonInputandOutput Exercise1.2  Openanewfileandcallitio.f95.  Typeinthefollowingprogram: program io real :: x,y,z print *, 'enter the values x,y and z' read *, x,y,z print *, 'the values you typed are for z,y,x are: ',z,y,x end program io  Executeitbypressing  YoucanenterthenumbersoneatatimeandpresstheEnterkeyeachtime.  Executetheprogramagain  Thistimetypeallthreenumbersononelineseparatedbycommas. Copyright©JanetANicholson2011 7 fortrantutorial.com Lookattheprintstatement print *, 'the values you typed are for z,y,x are: ',z,y,x Inthisstatement,weareoutputtingfourseparatethings,aliteralstringofcharacters, 'the values you typed are for z,y,x are: ' andthevariablesz,y,andx.Wemayoutputseveralitemsatonetime,providedtheyareseparated bycommas.  Exercise1.3 Thefollowingprogramhasanumberoferrors.  Createanewfilecalledbug.f95andthentypeinthefollowingprogramexactlyasshown.  Youcanalsodownloadthisfilefrom http://fortrantutorial.com/fortrantutorialexampleprograms/index.php  program bug this program is full of errors real :: a,b,c a = b + c read *,c print *,a end program simple Thecompilerwillreporttwoerrormessageswhenitattemptstocompile.Clickonthedetailsbutton. Eacherrorgeneratesamessage.   Doubleclickingonthemessagewill takeyoutothelineintheprogramwherethefaultoccurs.    Copyright©JanetANicholson2011 8 fortrantutorial.com   Correctthetwoerrors.  ClickExecute  Thereisnowonefurthererror,Platowillprovideayellowwarningalert.Watchthescreen carefully!Thewindowwillcloseandthentheprogramwillstarttoexecute.Somethingis notcorrecthowever…theprogramwill"hang".Itisactuallywaitingforyoutoinputavalue, becauseoftheline read*,c.Totheuseroftheprogram,thisisnotatallobvious–they mayhavethoughtthattheprogramhascrashed!  Typeinanumberthenpressenter  Theprogramreturnsanstrangevalue.Thisisan"executiontime"error.  Weneedtofindoutwhatthewarningmessagewas.Clickthe"compile"button(totheright ofthebinoculars).Thenclickthe"details"button.Platowilltellyouthatthevariablebhas notbeengivenavalue.  Correcttheprogramtogivebavalue,andthenexecutetheprogramagain.  Thereisstillaproblem.Thistime,itisaproblemwiththeprogram'slogic.  NeedaHint?Theprogramstatementsareexecutedsequentially. a=b+c read *, c print *, a Thestatementa=b+cdoesn'tmakesense,asatthisstageoftheprogram,wehaven'tyetgivena valuetoc.  Importantpointstonote  Therearetwotypesoferrorsassociatedwiththisprogram:compilererrorsandruntime errors.  Theprogramisalsouserunfriendly.Theprogramwaitsforinputwithouttellingtheuser whatisneeded. Fixtheruntimeerrorby:   readinavalueforb  correcttheorderofthestatements  maketheprogrammoreuserfriendly,  thencompareyourprogramwiththeonecalledbu gfixed.f95at  http://fortrantutorial.com/fortrantutorialexampleprograms/   1.8 MoreDatatypes–integerandcharacter Sofar,wehaveonlyusedreal(floatingpointnumbers)inourprograms.Wecanalsospecifythat numbersareintegerandcharacter.Programconvert,below,demonstratestheiruse.  Withinagivenrange,integersarealwaysrepresentedexactlywhereastheprecisionofrealnumbers islimitedbythearchitectureofthemachine.Therealvariabletypegivesus6figurede cimal precision.(Ifthisdoesn'tseemenough–don'tworrywe'llcomebacklateronwhenweexaminehow toincreasethenumberofdigitsofprecisioninSection4).  Charactervariablesholdstringsofcharacterslike 'A happy day was had by all' 'Yes' 'N' '3 + 4 equals 7' Copyright©JanetANicholson2011 9 fortrantutorial.com Whenthecharactervariableisdeclared,weshowthemaximumlengththatthestringcanoccupyby followingthenamebya*thenitsmaximumlength.Theexamplebelowhasamaximumlengthof10 charactersallowedforaperson'sname–thismightnotalwaysbeenough!Youhavetomakea judgementher e.  program convert !This example shows the use of integer and character variables. implicit none integer :: pounds,pence,total character :: name*10 print *,'What is your name?' read *,name print *, 'Hi ',name,'! Enter number of pounds and pence' read *, pounds,pence total =100 * pounds + pence print *,'the total money in pence is ',total end program convert  NOTEtheinclusionoftheline  implicit none   Byincludingitinyourprogram,FORTRANwillcheckthatyouhaveproperlydeclaredallyourvariable types.Inthebadolddaysofprogramming,declarationofvariableswasthoughttobeunnecessary andtheoldFORTRANcompilersusedanimplicitconventionthatintegershavenamesstartingwith thelettersinth erangei–n,alltheothersbeingreal.FORTRANstillallowsyoutodothisifwedon't includetheline,implicitnone.Timehasshownthatoneofthecommonestreasonsforerrorina programistheincorrectuseofvariables.   Alwaysuseimplicitno neatthestartofeveryprogram.    Exercise1.4 Withtheprogramconvertinsection1.5asaguide,writeaprogramtotestouteverythingyou've learnedsofar.Youmightincludedifferenttypesofvariables,forexamplereal,integer,and character.Includeinputandoutputusingreadandprint.Anexamplemightbeaprogramthatasks peoplequestio ns,includingthingsliketheirageandnameandsoon.Itcould,forexample,printout theiryearofbirthwithasuitablemessage.It'suptoyou,justuseyourimagination. Copyright©JanetANicholson2011 10 fortrantutorial.com  1.9 SavingthecontentsofOutputWindow Runyourlastprogramagain.Whentheblackoutputwindowopensrightclickonthe Platoiconinthetopleftcorner     Clickonedit  ClickSelectall  Clickcopy  OpenanewdocumentinWordorNotepadandclickpaste.     [...]... able to: Do arithmetic Start to use FORTRAN intrinsic functions Begin to understand program flow and logic Know how to test for zero – important! Learn more about good programming style 2.2 Assignment When we start programming, the similarity between mathematical equations and FORTRAN statements can be confusing Consider the following FORTRAN statements: Store the value 2 in memory location x Store... result Hint you need to declare a third variable for intermediate storage of the data (Check your program by examining program swap.f95 at http://fortrantutorial.com/fortrantutorial example programs/ 2.3 Arithmetic The arithmetic operators are +,plus and minus *,/ multiply and divide ** exponentiation (raise to the power) () brackets The order of precedence in FORTRAN is identical to that of mathematics... Nicholson 2011 17 fortrantutorial.com To get over this problem, we have to signal to FORTRAN that we want it to calculate the right hand side of the expression using real arithmetic If we want to keep x as integer data type, we could re write our expression as follows: y=x/3.0 The presence of a real number on the right hand side causes the right hand side of the expression to be evaluated using floating... typing and is prone to error Imagine if we had to deal with thousands of numbers! The way around this is to use arrays An array is a list that we can access through a subscript To indicate to FORTRAN that we are using an array, we just specify its size when we declare it real, dimension(100) ::x x(1) = 3 x(66) = 4 This snippet of code allocates 100 memory locations to the array x To access an individual... program twodra Copyright © Janet A Nicholson 2011 30 fortrantutorial.com FORTRAN actually allows the use of arrays of up to 7 dimensions, a feature which is rarely needed To specify a extended precision 3 dimensional array b with subscripts ranging from 1 to 10, 1 to 20 and 1 to 30 we would write: real (kind=ikind),dimension(10,20,30) :: b Exercise 5.4 Using a 4*4 array create an identity matrix, that... want to construct a table of values for z where z = xy for values of x in the range 1 to 2 in steps of 0.5 and y in the range 1 to 2 in steps of 0.5 Work through the next exercise which illustrates this: Copyright © Janet A Nicholson 2011 19 fortrantutorial.com Exercise 3.5 Copy program xytab.f95 to your filespace program xytab implicit none !constructs a table of z=x/y for values of x from 1 to 2... yourself and think carefully about its implications This program demonstrates how easy it is to get calculations wrong I’ll leave this to you to experiment to ensure that you fully understand the importance of properly declaring variables and the use of constants in FORTRAN programming A systematic approach to your programming will reduce the risk of errors as will running programs with test data that have... 2011 16 fortrantutorial.com 3 Loops 3.1 Aims By the end of this worksheet, you will be able to: Understand more about the use of real and integer variables and how to use a mixture of data types in expressions Understand how to re use code by looping Know how to control the number of times a section of code is executed by using a do loop 3.2 Mixing variable types Exercise 3.1 Copy divide.f95 Make sure... allocatable,dimension(:):: vector !note syntax - dimension(:) integer :: elements,i print *,'enter the number of elements in the vector' read *,elements allocate(vector(elements)) !allocates the correct amount of memory print *,' your vector is of size ',elements,' Now enter each element' do i=1,elements read *,vector(i) end do print *,'This is your vector' do i=1,elements print *,vector(i) end do deallocate(vector) !tidies... conditions end if 2.8 Other logical operators So far, all our tests have been for equality There are several tests we can make: == /= < >= equal to (there is no space between the equals signs) not equal to less than less than or equal to greater than greater than or equal to Copyright © Janet A Nicholson 2011 14 fortrantutorial.com 2.9 Multiple Conditions Suppose we need to test if x is greater than y and . Copyright©JanetANicholson2011 1 fortrantutorial.com   Introduction to Programming  using FORTRAN 95  http://www.fortrantutorial.com/       Theseworksheetsaim to provideanintroduction to programming. Thelanguagechosenforthisis FORTRAN 95. This isbecause FORTRAN isparticularlysuitableforscienceand engineering;itisalsoverywidelyavailable.  Theskillsyouacquireworkingthroughthesenotescanbe applied to anycomputinglanguage.Theconceptsyouwilllearn aresharedincommonwitheveryothercomputinglanguage.   Thisdocumentandalltheexamplesmaybefoundonlineat:  http://www.fortrantutorial.com/   ©JanetANicholson2011 Copyright©JanetANicholson2011. Canyouseewhatishappening? FORTRAN iskeepingth eintegerpartoftheanswerandthrowingthe restaway.  Makesureyouunderstandthis thoroughly! Copyright©JanetANicholson2011 18 fortrantutorial.com To getoverthisproblem,wehave to signal to FORTRAN thatwewantit to calculatetherighthand sideoftheexpression using realarithmetic.Ifwewant to keepxasintegerdatatype,wecouldre writeourexpressionasfollows:  . Typefirst.f95  1.4 Platoa programming environment  Copyright©JanetANicholson2011 4 fortrantutorial.com Platoisa" ;programming environment".WithinPlato,youcancreateandeditprogramsandgetthem to run.Plato'seditorisspecial–itunderstandsthesyntaxofvarious programming languages.Wetell Platowhichlanguageweare using whenwecreateouremptyfileandsaveitwitha.f95(FO RTRAN 95) extension.Providedyouhavegivenyourfiletheappropriateextension,Plato'seditorwillbeable to checkthesyntaxoftheprogram,highlightingthevariouskeywordsthatitknowsabout using a colourcode to distinguishbetweenthevariouselementsofthelanguage. Alwaysensurethatyourprogramfileshavea.f95extension 1.5

Ngày đăng: 24/10/2014, 20:52

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN