Fortran - University of jb/math190/ IN FORTRAN There are two main types of Fortran in common use: Fortran 77 and Fortran 90. The latter is an extension of the former, so that a Fortran 77

Download Fortran - University of  jb/math190/  IN FORTRAN There are two main types of Fortran in common use: Fortran 77 and Fortran 90. The latter is an extension of the former, so that a Fortran 77

Post on 05-Mar-2018




12 download

Embed Size (px)


<ul><li><p>PROGRAMMING IN FORTRAN</p><p>There are two main types of Fortran in common use: Fortran 77 andFortran 90. The latter is an extension of the former, so that a Fortran 77program will run on Fortran 90. We will be using the Gnu version of For-tran 77.</p><p>These notes are rather cryptic, but they do contain good examples.</p><p>1. The Environment</p><p>In order to run Fortran in the math lab, first click on the icon labelledFortran. This will give you a command prompt in your H: drive.</p><p>You will need to use an editor to create your program. The standardDOS editor works well. Type edit filename.f to start editing a file with thiseditor. The name of a Fortran program must end in .f or .for. Fortran iscase-insensitive, so capital letters are not distinguished from lower case ones.</p><p>Surely the most peculiar feature of Fortran 77 is its line structure, whichis a carryover from the days of punch cards. A punch card had 80 columns,and so does a line of Fortran code. A c in column 1 indicates a comment.Columns 25 are reserved for line numbers (usually blank). Column 6 isused only to indicate a continuation of a line too long to fit on one card.Columns 772 contain the instructions of the program. Columns 7380 arefor data only, and are ignored by the compiler. (This form is no longerrequired in Fortran 90, though it is sometimes used.)</p><p>Let us go through the steps of running a short program. First we edit inthe program, say hello.f.</p><p>program helloprint *, Hello, world!end</p><p>Exit the editor, saving the file. You can then compile the program by typingg77 hello.f. Compiling the program makes an executable program whichis by default called a.exe. The executable program is executed by typingjust the letter a. (In UNIX, the default name is a.out, and the executioncommand is a.out*.)</p><p>If you want to give the executable file a different name, compile the pro-gram with the form g77 hello.f -o greeting to make an executable file calledgreeting.exe, which is run by typing greeting. The executable file can becalled anything that is not the name of another file.</p><p>Date: September 1, 2005.</p><p>1</p></li><li><p>2 PROGRAMMING IN FORTRAN</p><p>Control-C interrupts the execution of a program, which is sometimesnecessary. You can print your fortran program using Notepad; the standardprint option doesnt work in our lab.</p><p>2. Variables and Operations</p><p>We now look at some Fortran program statements and discuss how vari-ables and functions are represented.</p><p>Comments are indicated by a c in column 1. Alternately, an excla-mation point (!) is used to indicate a comment; it may occur anywhere in aline, indicating that the rest of the line is a comment.</p><p>Types of variables. Fortran has integer, real, double precision andcomplex variables. The default type of a variable starting with i through nis integer, and otherwise the default type is real. It is normal programmingpractice to declare the type of all variables, with exceptions being made forshort programs and integer loop counters.</p><p>The types of variables are declared as in the following examples.</p><p>real a,b,cinteger max, counter</p><p>This makes a, b, c real variables and max, counter integer variables. Analternate form includes two colons:</p><p>real :: a,b,cinteger :: max, counter</p><p>Type declarations can also be used to dimension an array. The commands</p><p>real vec(20)integer mat(0:10, 0:10)</p><p>make a real vector vec(i) with subscripts 1 to 20 (so 1 is the default lowerbound), and an integer array mat(i, j) with subscripts 0 to 10. Likewise,</p><p>double precision sam(-5:5)</p><p>makes a double precision vector sam(i) with subscripts -5 to 5.The implicit statement makes all variables starting with given letters of</p><p>the same type. For example, the default types are equivalent to</p><p>implicit integer (i-n)implicit real (a-h,o-z)</p><p>In particular, the command implicit integer (a-z) is useful for mathematicalprograms involving only integer variables. Otherwise, the implicit commandis best avoided.</p><p>Assignment The equal sign = gives the variable on the left hand sidethe value of the number or expression on the right hand side, as in x = 1.</p><p>READ The simple (unformatted) read statement allows the user to typein values for the variables. Sample:</p><p>read *, a,b,c</p></li><li><p>PROGRAMMING IN FORTRAN 3</p><p>You would then enter the values of a, b, c separated by returns. The asteriskin both read and print statements means to use the default format for inputor output.</p><p>To input a vector, you can use the implicit loop form:read *, (dog(i),i=1,5)</p><p>PRINT The PRINT statement, which prints the variables or expressionsfollowing it to the screen, has a similar form:</p><p>print *, To be or not to be?print *, x = , xprint *, a,b,cprint *, (dog(i),i=1,5)</p><p>Note that either single or double quotes may be used for strings. Later wewill see more complicated forms of the READ and WRITE statements.</p><p>STOP and END The stop statement stops execution of the program.The end marks the end of the main program or a subroutine.</p><p>Mathematical operations. Fortran has the following standard opera-tions. The trig functions use radians.</p><p>(1) x + y for addition.(2) x y for subtraction.(3) x y for multiplication.(4) x/y for division.(5) x y for exponentiation.(6) sin(x) for sine.(7) cos(x) for cosine.(8) tan(x) for tangent.(9) atan(x) for arctangent.</p><p>(10) sqrt(x) for square root.(11) abs(x) for absolute value.(12) exp(x) for ex.(13) log(x) for the natural logarithm (base e).(14) mod(x, n) for x mod n.</p><p>Warning: If m and n are integers, then m/n will be truncated to its integerpart. Thus 1/6 will be evaluated as 0, and 7/6 becomes 1. This is a usefulfeature in advanced programming, but is also a common source of errors.For constants, it can be avoided by using decimal points, e.g., 1./6.. Forvariables, it can be avoided by using another variable name, e.g., realm = m,assuming that there was some reason not to declare m to be real in the firstplace.</p><p>3. Arrays</p><p>Array declarations in Fortran go at the beginning of the program, beforeany executable statement. Vectors and arrays can be declared using eitherdimension or a type declaration, as in these examples.</p></li><li><p>4 PROGRAMMING IN FORTRAN</p><p>dimension ke(10)real dog(10,10)</p><p>The second form, indicating the variable type, is preferred. Note that in theabove example the vector ke(j) would be of integer type.</p><p>Because vectors and arrays are declared at the beginning, they must begiven a fixed size, e.g., ke(10) rather than ke(n). There is a way aroundthis, but it is a little complicated.</p><p>Finally, in Fortran the default lower limit is 1 (rather than 0). A colon isused to indicate a range of subscripts, as in:</p><p>real cow(0:100, 0:100)integer bat(-5:5)</p><p>4. DO Loops</p><p>A loop begins with a do statement, and ends with either end do or aprescribed statement number (replacing NEXT). The following examplesillustrate the usage.</p><p>sum=0do i=1,10sum=sum + i**2end doprint *, sum</p><p>The same program could be written as follows, using line numbers.sum=0do 5 i=1,10sum=sum + i**2</p><p>5 continueprint *, sum</p><p>As a matter of form, loops of the second form should end with a continuestatement, a non-executed statement which identifies the end of the loop.</p><p>If you only wanted say the even terms, then you could replace the secondline by</p><p>do 5 i=2,10,2where the last number indicates the step size. The step size can be positiveor negative.</p><p>You can use variables for the limits on the loop counter, as indo 5 i=min, max</p><p>Finally, loops can be nested. Different loops can end on the same continuestatement.</p><p>do i=1,10do j=1,10a(i,j)=i+jend doend do</p></li><li><p>PROGRAMMING IN FORTRAN 5</p><p>ordo 5 i=1,10do 5 j=1,10a(i,j)=i+j</p><p>5 continue</p><p>5. Logical expressions</p><p>A logical expression is a relation between variables which can have a valueof TRUE or FALSE. These are used with IF...THEN and DO...WHILE todecide whether to execute certain steps of the program. In Fortran, logicalexpressions and operators are indicated by periods on both sides. The basicrelations and their meanings are:</p><p>.lt. means less than</p><p>.gt. means greater than</p><p>.le. means less than or equal to</p><p>.ge. means greater than or equal to</p><p>.eq. means equals</p><p>.ne. means not equal to</p><p>.or. means or</p><p>.and. means and</p><p>.not. means notWe will use some of these expressions in the next section.</p><p>6. DO WHILE....</p><p>DO WHILE.... loops in Fortran are another way to perform iterations,with the logical condition replacing the counter. The form is illustrated inthe following two examples, which give a rough way to approximate</p><p>10.</p><p>x=1do while (x** do</p><p>c x**2 will be greater than 10or</p><p>x=1do 5 while (x**</p><p>5 continue</p><p>7. User-Defined Functions</p><p>Fortran has two ways in which you can define functions. If the functionhas a simple expression, then you can just insert a line at the top of theprogram, before any executable statement. For more complicated functions,you should use a function subroutine. The function subroutine is a separate</p></li><li><p>6 PROGRAMMING IN FORTRAN</p><p>section of the program, but is normally edited in the same window as themain program. In the following example, the function f(x) is defined theformer way, and g(x) the latter.</p><p>program tatef(x)=x**2print *, What is a?read *,aprint *, f(a) = , f(a)print *, g(a) = , g(a)end</p><p>function g(x)g=x**nreturnend</p><p>The first end statement ends the main program, the second ends the func-tion. With most Fortran 77 compilers (but not the one on uhunix2), thefirst end could be end program or end program tate, while the second couldbe end function or end function g(x).</p><p>Functions can use local or global variables, but the global variables mustbe indicated as common.</p><p>program powerscommon nprint *, What is x?read *, xprint *, What is n?read *, nprint *, x**n = , h(x)end</p><p>function h(x)common nh=x**nreturnend</p><p>Of course, a simpler way would have been to use a function of two variables,h(x, n). In passing or sharing vectors or arrays, just use the array name,e.g., common vec.</p><p>8. IF...THEN</p><p>This allows you to perform certain steps only when a logical expressionis TRUE. There are two forms of the IF statement, the one-line form andthe multiline form. A one-line IF statement does not contain the keyword</p></li><li><p>PROGRAMMING IN FORTRAN 7</p><p>THEN, while the multiline form does. ELSE is an allowable option. Thefollowing examples illustrate the usage.</p><p>Example 1:read *, xif (sin(x).lt.0) print *, Try again!</p><p>Example 2:read *, xif (sin(x).ge.0) then</p><p>y=sqrt(sin(x))print *, sqrt(sin x) = , y</p><p>end ifExample 3:</p><p>read *, xif (sin(x).ge.0) then</p><p>y=sqrt(sin(x))print *, sqrt(sin x) = , y</p><p>elseprint *, Try again!</p><p>end if</p><p>9. Labels and GOTO</p><p>The GOTO (line number) command allows you to skip around in theprogram. They should be used sparingly, but can be useful, especially inconjunction with IF statement. For example, the command</p><p>if ( goto 200skips to the line labeled 200 if z &gt; 5.</p><p>Subroutines (discussed later) are often a better option than GOTO.</p><p>10. WRITE and FORMAT Statements</p><p>We use the write command with a format statement in Fortran to controlthe output. While these can get complicated, the most commonly usedoptions are simple and easy to use. A typical write statement is</p><p>write (*,200) x,y,zThe first position inside the parentheses tells the computer where to write;the * indicates the terminal. If you wanted to write to a file, you would usethe number assigned to that file (see below). The second position gives theline number of the format statement to be used. In this case, the formatstatement might be something like</p><p>200 format(3f10.4)This would indicate three numbers with at most 10 places (counting the signand the decimal point), with 4 places after the decimal. The x, y and z areof course the variables to be printed.</p></li><li><p>8 PROGRAMMING IN FORTRAN</p><p>The most common field descriptors used in format statements are thefollowing.</p><p>(1) iw denotes an integer of length at most w, e.g., i4 for an inte-ger between -999 and 9999. 20i4 denotes the places for 20 suchintegers.</p><p>(2) fw.d denotes a real number in decimal form of length at most w withd places to the right of the decimal, e.g., f9.4 for -132.4552.</p><p>(3) ew.d denotes a real number in exponential form of length at most wwith d places to the right of the decimal, e.g., e9.4 for 0.1234E+2.Note that w d + 5 is required.</p><p>(4) Dw.d denotes a double precision number in exponential form oflength at most w with d places to the right of the decimal.</p><p>(5) wx denotes that w spaces are to be skipped (left blank), e.g., 4x.Strings (in quotes) may be placed between the field descriptors, separatedby commas.</p><p>Here are some examples.write (*,20) n,x,y</p><p>20 format(2x,i4,2f10.4)write (*,30) f(x)</p><p>30 format(The function value is ,f12.5)To print an integer matrix, we might use the following.</p><p>do 50 i=1,nwrite (*,40) (m(i,j),j=1,n)</p><p>40 format(20i4)50 continue</p><p>In order to write to a file, you must first open the file and assign it a unitnumber. For example, the following command opens the file dog.out andassigns it the unit number 7.</p><p>open(unit=7,file=dog.out)To write to the file, we would refer to its number in the first entry of thewrite command:</p><p>write (7,10) f(x)10 format(2x,y = ,f12.5)</p><p>The file may be closed with the command close (unitnumber), e.g., close(7).</p><p>11. Subroutines</p><p>Subroutines in Fortran work just like independent subprograms, with theproperties already noted under user-defined functions: it is not necessaryto declare them, they must contain the line return before end, and usingcommon for global variables.</p><p>The following example illustrates a simple subroutine.program calculator</p></li><li><p>PROGRAMMING IN FORTRAN 9</p><p>print *, What are x and y?read *, x, ycall add(x,y,z)print *, The sum is , zend</p><p>subroutine add(a,b,c)c=a+breturnend</p><p>The return command may also be used to return to the main program fromsomewhere in the middle of the subroutine.</p><p>Assignment 8. Write a fortran program to sort a list of numbers usinga bubble sort.</p><p>Assignment 9. Write a program that will compute ba f(x) dx for a con-</p><p>tinuous function f(x), with accuracy 104. Format the answer accordingly.</p></li></ul>