Sie sind auf Seite 1von 20

Introduction to FORTRAN 90 Programming for ME 410/610

Caleb Barnes ME 410 Fall 2010

Introduction
In this class you will need to have a basic understanding of the FORTRAN 90 programming language. This manual was comprised of a limited set of FORTRAN 90 syntax to specifically assist you with the projects in this class. The FORTRAN 90 programming language is certainly not limited to the contents of this manual. For a more in depth study please refer to Chapman Fortran 95/2003 for Scientists and Engineers or the numerous online resources. Other resources provide brief discussions and examples of the basic FORTRAN syntax. The goal of this manual is to provide a more detailed description of the FORTRAN syntax in a compact setting and also train the reader to adopt good programming practices as per the authors experience. This manual is written based on the FORTRAN 90 standard and beyond -- most of this does not apply to the FORTRAN 77 standard.

The Basics
To write the simplest of FORTRAN programs you will need to know a few keywords. The following keywords are presented in bold and all caps for clarity. When programming, it is not necessary to type the keywords in bold or all caps. PROGRAM this statement marks the beginning of the specific program you are writing and is followed by the name of the program you are writing. The name may be anything you want, but must be on word or several words separated by the _ character. It must be closed with an END or END PROGRAM statement. All contents of the program must be contained between the PROGRAM and END PROGRAM statement. IMPLICIT NONE this statement forces all variables to not be associated with any variable type such as INTEGER or REAL. Implicit means that the variables are not directly defined by the user and are instead assumed by the compiler. Setting the implicit variables to none will allow the compiler to tell the reader that specific variables have not been explicitly defined by the coder. This statement is not necessary in any program but will prevent the reader from accidentally defining an integer variable as a real or vice versa. By default the compiler will assume variables as a certain variable type based upon the first letter in the variable name. For example, a variable named i will be assumed as an integer unless specifically defined otherwise. This should be the first thing included after the PROGRAM statement. INTEGER this sets the variable type as an integer value. This statement followed by variable names will define the variables listed as explicitly integer values. The definition of an integer value will be given later.

REAL this sets the variable type as a real value. This statement followed by variable names will define the variables listed as explicitly integer values. The definition of a real value will be given later. END PROGRAM this signals the end of the program you are writing. A program may be ended with the END statement only, but this can make a program confusing as there will be many END statements throughout most programs. The END PROGRAM statement may also be followed by the name of the program for more clarity. This may allow your program to become somewhat clearer and balanced, but it is not necessary for the program to work. STOP this statement signals the main program to stop execution. This is often used at the end of the program to ensure the operation terminates or in the case of error checking. If you are checking for an error in your code as it runs you can use this statement to terminate the program when the error is encountered. Comments Another item of interest are comments. Comments are lines in the code that allow the user to annotate the code for clarity. A comment might be used to label a certain section of code, describe a variable, or for aesthetics. The use of comments is highly recommended as it will help both the reader and the instructor understand what you are doing in your code. It is particularly useful with end statements for conditionals and loops to keep track of which loop and conditional is being ended. A comment may be placed almost anywhere in your code and is signaled by typing the ! character first. A comment may be placed inline with code if placed at the end of the line. Shown below is an example of how all the keywords might be used in a program. This program is named main and is terminated with the END PROGRAM statement followed by the program name. The IMPLICIT NONE statement is listed first followed by the INTEGER and REAL variable allocation statements. Notice that both REAL and INTEGER are followed by two colons and that member of the list of allocated variables are separated by commas. Notice also that comments are included both separately and inline with the code.

Figure 1. Example of starting a program.

Variable Types and Basic FORTRAN Math


Two variable types were introduced in the previous section. In this section we will define these variable types and discuss how to use them in simple mathematic operations.

Integer values these are simple whole numbers and never include decimal values. Integer values can be positive or negative. If integer division is performed the resulting value will be truncated. By truncated we mean that the decimal value will be removed (not rounded). There is a large difference between truncation and rounding. For example, the operation 7/4 is equal to 1.75. If this operation is rounded then 7/4 = 2. However, with truncation the decimal values are simply removed so 7/4 = 1 in integer math. It is extremely important to keep this in mind when performing mathematical operations in FORTRAN. Integer values are generally used as counting numbers and indexes. Common uses include the location inside an array or the current iteration inside a loop. Real values these values hold floating point numbers. That is, numbers that include decimal places. Real values may be positive or negative and have a limited level of precision (sufficient for many applications). Real number division operates as you would expect. As per the example above, the operation 7.0/4.0 would store the value 1.75 as opposed to the value of 1 for integer division. Addition addition is performed by placing the + character between two values. For example, a3 = a2 + a1. Subtraction subtraction is performed by placing the - character between two values. For example, a3 = a2 a1. Multiplication multiplication is performed by placing an * in between two values. Multiplication cannot be performed without this character. For example a3 = a2(a1) will produce an error and should instead be written as a3 = a2*a1. Division division is performed by placing the / character between two values. For example a3 = a2/a1. Powers contrary to other interfaces such as MATLAB, powers are NOT defined using the ^ character. Instead powers are defined using **. For example, a3 = a2**a1 would define a3 as a2 to the a1th power. Integer values may be used for powers without the worry of truncation or mixed variable type math. In fact, the use of integers as powers is encouraged whenever possible. SQRT the square root of a value may be obtained in two ways. First, using a power of 0.5 as in a3 = a2**(0.5) or using the SQRT intrinsic function. This is performed on a number in the following manner. a3 = SQRT(a2). The two examples are equivalent statements. Intrinsic functions are functions defined within the compiler that may be called by any program, subroutine, or module. User functions may also be defined (this discussed in a later section) and used similarly. Mixed variable type math this should be avoided as much as possible as the results are difficult to predict and are most often not what you intended. Integer values can be converted to real values inline and vice versa to avoid mixed variable type math while using mixed type variables in a calculation. Defining values This should be done for any value used in a calculation later in your program. Integer type variables are defined using integer values such as 1, 2, 3, -4, etc NOT 1.0 or 2.0. Real type variables are defined using real numbers such as 1.0, 2.0, -4.0, etc. NOT 1, 2, or -4. Numbers themselves carry an implicit definition. You should always ensure that when writing a number it is written in either integer or real form. A number in real form must be followed by a decimal, the zero is 3

optional. Otherwise your computer might assume you intended an integer operation. A number in integer form must not have a decimal anywhere in the number. The following figure demonstrates everything up to this point discussed in this section. The real variable a3 is used to store real value calculations performed using the different mathematical operations. Notice that real values are set using decimals while integer values are set using no decimals. Also, notice that line 25 shows an incorrect way of performing mixed type operations while line 26 shows a correct way for carrying out that operation. When the program is finished, only the last calculation is stored in the memory space for a3.

Figure 2. Example demonstrating FORTRAN math.

Loops and Conditionals


In FORTRAN 90 there are two types of loops that you will have the option of using. These are the DO loop and the DO WHILE loop. Inherently, both loops do the exact same thing, but operate in different ways. Loops are used for repeating operations such as increments or cycling through indexes in arrays. In a physical sense, loops might be used to perform time stepping or space stepping in a calculation. For many numerical methods loops are also used to perform iterations until a solution is converged. Loops will become incredibly important when we begin to use arrays. The following are definitions and examples of loops in FORTRAN 90. DO The do loop is terminated by an END DO statement and repeats all code contained within for a specified number of iterations. The DO loop is often called a FOR loop in other programming languages 4

such as MATLAB. The DO statement is followed by an integer index and a range of integer values (ex: i = 1, 20 cycles through iterations 1, 2, . 19, 20). The first value in the range is the starting value, this can be any integer value, but preferably 1 or higher. The second value is the ending value and the DO statement will repeat all contained code until the index reaches this value. A third integer value may be included in the index and this controls the step size. (ex: i = 2, 20, 2 cycles through 2, 4, 6, . 18, 20) The DO statement is the most straightforward style of loop and is encouraged over the DO WHILE loop for most applications as it will always end at some point. If no index value is included with the DO statement then the loop will cycle indefinitely. If this is done, a conditional expression must be included somewhere inside the loop with a criterion for ending the loop. There is no point in using a DO loop in this manner as this is the same function as a DO WHILE loop. DO WHILE -- The do while loop is terminated by an END DO statement and repeats all code contained within until a specified condition is reached. The DO WHILE statement is followed by a conditional expression which governs the loop continuation. This logical expression must be carefully chosen and written otherwise the loop will never terminate and the user will be required to terminate the program. The conditional statement is contained inside parentheses following the DO WHILE statement. The rest of the loop operates in a manner similar to the DO loop. More information on conditional statements will be given later. To understand the operation of the DO WHILE loop think of it in terms of a sentence: DO this stuff (contained code) WHILE this is true (logical expression). < -- less than symbol. Used in a logical expression to compare two values. If the value on the left is not less than the value on the right, the logical expression returns a Boolean value of FALSE. It will also return FALSE if both values are equal. Boolean values are basically logical checks to tell the computer whether or not a statement is true or false. The old form for this was .LT. in FORTRAN 77. > -- greater than symbol. Same as above only the opposite is true. If the value on the left is not greater than the value on the right, the logical expression returns FALSE and vice versa. Additionally, this conditional will return FALSE for two equal values. The old form for this was .GT. in FORTRAN 77. <= -- less than or equal to symbol. This operates similarly to the less than symbol only the TRUE statement will include equivalent comparisons. >= -- greater than or equal to symbol. This operates similarly to the greater than symbol only the TRUE statement will include equivalent comparisons. == -- equivalence symbol. This checks if two values are equal. If they are equal it returns TRUE and if not it returns FALSE. The old form for this was .EQ. in FORTRAN 77. /= -- non-equivalence symbol. This checks if two values are unequal. If the two values are not equal then TRUE is returned, but if they are equal it returns a statement of false. The old form for this was .NE. in FORTRAN 77. .OR. this is used to include two logical expressions in to one. If using statements like .OR. in FORTRAN it is easier to think of in terms of a sentence. IF this statement is true .OR. this statement is true THEN do this. For this IF statement, the operation will be performed for either conditional.

.AND. this is used to include two logical expressions in to one. If using statements like .AND. in FORTRAN it is easier to think of in terms of a sentence. IF this statement is true .AND. this statement is true THEN do this. For this IF statement, the operation will be performed only if both conditionals are true. IF If statements are incredibly useful and can give the user a large amount of control over the program operation and flow. The complexity of an IF statement can range from a single line logical expression and command to a nested structure of multiple conditional statements. Multiple examples will be given in the following figure. EXIT following the IF statement, this is a good place to introduce the EXIT statement. The EXIT statement is used to terminate a loop in operation. This is generally use in DO loops as an exit criteria and must be accompanied by an IF statement that signals the exit criteria. This too will be used in the following example.

Figure 3. Example demonstrating loops and conditional statements. The above example is a continuation of our previous examples with the items discussed in this section added in. The example is split into five sections labeled as items. We will discuss each item sequentially.

ITEM 1 demonstrates a simple use for a DO loop. The variable a1 is initialized as 0.0. Inside the loop the value of a1 is incremented by 1.0 each iteration. The final value of a1 is 10.0. Notice that the ENDDO statement is followed by a comment containing the index value. This is done to ensure anyone reading the code, including the writer, knows that ENDDO statement goes with that index value. This is incredibly useful for nested DO loops and is highly encouraged for the reader. ITEM 2 demonstrates the use of a DO WHILE loop. In this loop a2 is incremented by a value of 2.0 each iteration. The conditional statement following the DO WHILE loop is interpreted as do this operation while a2 is less than or equal to 30.0. If a2 never exceeded a value of 30.0 this loop would continue indefinitely. ITEM 3 demonstrates a simple one-line conditional. This is interpreted as If a2 is equal to 30.0 then set a3 equal to 5.0. If a single conditional is used to control a single command, the one line conditional statement is a simple and compact way of performing this operation. If two commands are used then the full IF THEN structure would be necessary as used in ITEM 5. ITEM 4 demonstrates the use of a conditional as an exit criterion for a DO loop. In this loop the conditional instructs the loop to terminate once the value of a1 exceeds a value of 40.0. ITEM 5 shows the full structure of the IF statement. Multiple logical expressions are used in the first expression. If one of the two logical expressions are not true then the second criteria is used. If none of the above logical expressions are true then the a4 is set equal to 4.0. The best way to think about this statement is in the form of If a3 is equal to 5.0 and a1 is greater than 40 then set a4 equal to a2, else if a3 is not equal to 5.0 then set a4 equal to a1, else if none of the above is true then set a4 equal to 0.0.

Arrays
Both real and integer values may be assigned as arrays. In other words one variable name may be used to store a larger set of data. Arrays may be used to store a single column of information or multiple dimensions. A one dimensional array is defined as an array with only one index while a two dimensional array is defined as one requiring two indexes. This is incredibly useful in numerous applications and will be encountered heavily in the projects for this course. In order to use an array, it must first be defined with a dimension and size. DIMENSION the dimension statement is included in the variable allocation statement following either the INTEGER or REAL statements. DIMENSION is followed by the size of the array enclosed in parentheses. This may look like DIMENSION(5) for a five element one dimensional array, or DIMENSION(3,3) for a 3x3 two dimensional array. If you are not initially sure of the array size or are allocating arrays of various sizes the DIMENSION may be written as DIMENSION(:) for a one dimensional array or DIMENSION(:,:) for a two dimensional array. The colon index can be incredibly useful in FORTRAN 90 programming and its uses will be discussed later. This sets the dimension of the array, but leaves the size open-ended. DIMENSION statements in this form must be followed by the ALLOCATABLE qualifier and later allocated when the array size is known and before the array is used. DIMENSION statements that are directly defined take up a specific space in memory while undefined dimension arrays can be unbounded if not allocated correctly before used. If an unallocated array is used 7

it can potentially cause a memory overflow and terminate your program. This error is not always obvious and may take the reader some time to realize. For this reason, it is very important to carefully allocate all arrays appropriately. ALLOCATABLE this qualifier must accompany any DIMENSION statements with an undefined dimension size. This qualifier allows the user to allocate a memory space for an array at a later time. ALLOCATE the ALLOCATE statement is used to allocate allocatable arrays. The statement is followed by the list of allocatable arrays and their sizes contained in parentheses. A straightforward demonstration will be presented in the example for this section. DEALLOCATE the DEALLOCATE statement is used to free memory space associated with allocatable arrays. This should always be used on allocated arrays at the end of the program to free the memory space especially when using subroutines. Most compilers will free the memory space by default when the program is terminated, but this should always be used in subroutines and is still a good practice to use in the main program as well.

Figure 4. This example demonstrates the use of arrays 8

The above example demonstrates the basic methods of allocating arrays and some simple uses. First, a1 is directly allocated as a five element one-dimension array, while a2 and a3 are allocated directly as 3x3 element two-dimension arrays. Variables a4 and a5 are defined as allocatable one-dimensional arrays and a6 is defined as an allocatable two-dimension array. Line 12 holds the allocate statement. Multiple arrays of different sizes may be allocated using the same line. Variable a4 is defined here as a 5 element array where elements are numbered 1, 2, 3, 4, 5. However a5 is allocated differently. The form of the size for a5 is shown as 1:10. This use of two numbers separated by a colon signifies a range of numbers as indexes for this array. This allows a greater level of flexibility in allocation. If 2:8 was used the size would be 7 with elements would starting with 2 and ending with 8. Additionally, 0 may be used as well as an element number if 0:4 was used. This would allow for a 5 element array numbered 0, 1, 2, 3, 4. This notation for allocating variables can complicate the allocation space but it leaves no doubt as to how the array is being defined. Next, several examples of initializing the values in arrays is shown. There are two ways to accomplish this. The first is to cycle through each element using a DO loop for a one dimensional array or a double nested DO loop for a two dimensional array. This is a perfectly acceptable way of setting element values, but it has several disadvantages in that it takes more time to write, takes more space, and is slightly less straightforward than the alternative. The second way to initialize elements is using the : notation. Basically, this performs the operation to every element in the array. For this case, it sets every element in a1 to 1.0 and every element for a4 to 2.0. It may be applied similarly to two dimensional arrays. In this case every element in both dimensions in a2 is set to 1.0 and 2.0 for a3. The same methods as applied above may also be applied to math operations. The last example shows every element in a1 being increased by the corresponding values in each element of a4. Similarly, an example for the two dimensional arrays is shown using subtraction. Using the colon notation requires that the set of data between two arrays have the same size and shape. However, the colon notation may be used for arrays of different size and shape if the more specific form of colon notation is used. Line 43 shows that each element in the 5 element array a4 is multiplied by the first 5 elements of the 10 element array a5. This is done using 1:5 which tells the computer to only apply the operation to elements 1:5 of the involved arrays. Last, the memory space used by arrays allocated using the ALLOCATE statement are deallocated using the DEALLOCATE statement.

Subroutines and Modules


We will now introduce two new concepts that are very useful in complex programs: SUBROUTINE and MODULE. We will begin our discussion with the definitions of the terms used with subroutines. Note that in this discussion the calling program refers to the program from which the subroutine was called. This may be the main program or another subroutine. SUBROUTINE a subroutine is a subprogram written separately for use in the main program or for use by other subroutines. The subroutine is not located within the main program. It is instead located before or after the PROGRAM and END PROGRAM statements. The format of a subroutine is very similar to a program except that it requires inputs to be used. Subroutines are primarily used to simplify the main 9

program and to make a chunk of code that is frequently repeated easier to use. Also, subroutines may be used to transfer a chunk of particularly useful and general code to other programs without much effort. The SUBROUTINE statement is followed by the name of the subroutine and the input/output variables listed inside parentheses. Inputs and outputs in a subroutine are, for our purposes, a just list of arguments referring to memory spaces that may be altered inside the subroutine. It is easier to think about the subroutine inputs/outputs this way. Some of the arguments may be used to make a calculation within the subroutine, while others are used to hold the final values resulting from the routine for use in the calling program, and some arguments may be used for both input and output. Basically, the arguments are shared memory spaces that may be accessed or altered by the subroutine. Any variable defined inside the subroutine that is not also an argument is local to the subroutine only and will be forgotten at the end of the subroutine operation. RETURN the return statement behaves much like the EXIT statement in that it signals the program to exit the subroutine and return to the main program when this command is sent. END SUBROUTINE this statement signals the end of the subroutine and is the subroutine equivalent of the END PROGRAM statement. Likewise, this may also be followed by the name of the program for clarity. CALL the CALL statement is used to activate a subroutine. This is followed by the name of the desired subroutine and the corresponding arguments as they appear in the main program. When the CALL statement is encountered the program enters the specified subroutine and executes the subroutine code. The arguments must be listed in the call statement in the same order as the arguments are listed with the SUBROUTINE statement. Additionally, the arguments do not need to have the same name as listed with the subroutine, but they must have the same type and dimension as used in the subroutine.

10

Figure 5. This example demonstrates the use of subroutines The above example demonstrates the use of a simple subroutine in a simple program with a diverse range of arguments. In the program, the integer i' or any other integer holding a value may be used to allocate the size of an allocatable array. The value a holds a single real value while b and c hold one dimensional arrays of size i. The value d holds a 3x3 two-dimensional array. Next the subroutine is called using the CALL statement followed by the subroutine name. Notice that the arguments are listed as they are named in the calling program and not as they are named in the subroutine listing. Also note that variable names used in the calling program may be reused in a subroutine in a completely different manner without consequence. Remember that the subroutine behaves as a separate program using inputs from another program. Additionally, the variable types of the variables in the CALL statement are the same as the variable types listed in the subroutine listing. The arguments in the subroutine are a1, a2, a3, a4, and k. Again, these are different names of variables from the calling program, but they refer to the same memory space. Any changes to these variables in the subroutine will affect their corresponding value in the calling program. Each argument must be defined 11

with a variable type in the subroutine. Argument arrays are not defined with a specific array size and instead are defined with DIMENSION(:) and without the ALLOCATABLE qualifier. This does not cause a problem in the subroutine because the argument arrays will assume the size of the corresponding array in the calling program. The subroutine includes a new real value named b1 and a new real allocatable array named b2 for use exclusively within the subroutine. Both of these values will be forgotten once the subroutine completes its operation. This array is allocated using the integer argument k. This trick may be used to ensure that temporary arrays used within a subroutine have the same size as the argument arrays from the calling program or any specific size as deemed necessary by the calling program. The specifics of the mathematic operations in the subroutine are of little significance at this point in the discussion; for more detail on this return to an early portion of this text. The main point is that all of the a values modified in the subroutine will remain modified when returning to the calling function. MODULE a module is a convenient way of modularizing a set of subroutines, variables, and variables types that is accessible by the main program and any subroutines located outside of the module itself. A module contains all these things in a neatly packaged format that may be transferred to another program and used with little to no modification to the module itself. You might use a module in cases where you are writing several similar programs that use the same set of variables, arrays and subroutines so that this portion of code does not need to be rewritten. Also, if a subroutine uses the module, variables included in the module do not need to be listed as arguments in the subroutine; even if the variable or array is intended as an input or an output. Variables declared or set in the module are shared with every portion of your program. The MODULE statement is followed by the module name and terminated with the END MODULE statement. END MODULE This statement is similar to the equivalent statements used to end the main program and subroutines. Likewise, this one signals the end of the module. USE this statement activates the module for the main program or a subroutine. The USE statement is followed by the name of the module to be used. This should be the first thing listed in your program or subroutine, even before the IMPLICIT NONE statement. CONTAINS This statement follows the variable declaration statements but precedes any subroutines included in the module. The CONTAINS statement must be used before inserting subroutines in order to specify that the module contains those subroutines. PARAMETER this statement is a qualifier included with variable types. PARAMETER is introduced here because it is often used with variable declarations in the module. The PARAMETER qualifier is used to set a variable, or array as an unchangeable parameter. This is often used as a failsafe to prevent specific values from being changed. You might use this in an engineering problem to define values of properties such as thermal conductivity or elasticity.

12

Figure 6. This example demonstrates the use of a module Above is a simple example of how modules may be used. Notice that this example is the same as the one given for subroutines only except this time the subroutine is included with the module. The integer variable i' has been relocated to the module and given the PARAMETER qualifier. This will allows the integer value to be defined once for the main program and all subroutines that use the module, therefore it is not allocated in the main program and it has been removed as an input to the subroutine. The PARAMETER qualifier prevents the integer value i' from being changed at any point in the program. Additionally, the real value a was declared in the module and consequently is not declared in the main program nor listed as an input to the subroutine or declared. This real value is not given the PARAMETER qualifier because it has a value that is intended to be modified. The subroutine is separated from the variable declaration statements in the module by the CONTAINS statement and the 13

module is ended with the END MODULE statement followed by the module name. Again, the module name in this statement is optional.

Input/Output
The last section in this manual will deal with data input/output in FORTRAN programming. Data output allows the writer to make data from the program visible during operation or upon the programs completion. It also allows the programmer to store the data for post processing such as plotting. Data input allows the user to take a data file previously created and read information into the current program. Data input is useful in many situations such as cases where numbers from a table are used or making further calculations on the output from another program. Some simple input/output syntax is provided here for your reference. PRINT the print statement is a simple way of writing information to the screen. It used by following the print statement with an asterisk comma and then the list of variables to be printed (ex: PRINT *, a, b). Additionally, text strings may be printed using this statement. This is done in the variable list by enclosing the text with single quotes. (ie: PRINT *, Variable 1: , a). This would print the string Variable 1: and then the value of a. WRITE the WRITE statement is a much more powerful form of output than the print statement. The WRITE statement can not only print to the screen, it may also print to a data file and accept customized formatting for the output. The write statement is followed by two numbers enclosed in parentheses and then the list of variables (ie: WRITE(5,10) a, b, c ) The first number is the label associated with the output file the data is to be written to while the second number is associated with the formatting label. To print the data to the screen you would replace the first number with an asterisk and to have open formatting you would replace the second number with an asterisk. If both numbers are replaced with asterisks then the WRITE statement behaves the same as the PRINT statement as given above. READ the READ statement is the way data is read into a running program. The READ statement allows for user input from the keyboard or for input from a text file. The format is similar to the WRITE statement in that it is followed by the label and format numbers enclosed in parentheses and then the list of inputs (ie: READ(15,20) a, b, c ). If an asterisk is used in the first position the input is prompted from the keyboard and the program operation will pause until the user provides an input. If a number is listed in the first position the program will take the input from the data file associated with that label. If an asterisk is placed in the second position then the formatting will be set to the default open form. This is recommended. FORMAT this statement is presented here for informative purposes only, but will not be discussed in context or detail as it is not necessary for anything we will do in this class. The FORMAT statement is preceded by a label number and followed by a list of formatting commands enclosed in parentheses. The purpose of this statement is to improve the appearance of the program output. Please refer to another reference for more information on this topic. OPEN this statement is used to open a file for data input or output. A file must be opened before it may be read from or written to. The OPEN statement is followed by the label number and the file name enclosed in parentheses as shown here (ie: OPEN(10, file = data.dat) ). The label associates that data 14

file with a number for use with READ and WRITE statements and allows for multiple data files to be open simultaneously. If the file name specified does not exist in the current directory (where your .f90 file is located) it will create the file, otherwise it will write over the data in the file that previously existed. It is important to note here that there are more commands that go along with the OPEN statement that are not presented in this manual and are not necessary for this class. Please refer to another reference for more information on this topic. CLOSE this statement is used to close an open data file. It is good practice to always close a data file when is no longer needed. The CLOSE statement is followed by the files label number enclosed in parentheses (ie: CLOSE(5) ). READ and WRITE Statements in Loops A further discussion on the function of READ/WRITE statements is necessary before we continue to examples. The point that needs to be made is that the READ and WRITE statements read or write one row of information each time they are called. Therefore, if it is necessary to read/write multiple rows of data (as is almost always the case) , it will be necessary to use these statements in conjunction with loops. For example: the statement WRITE(5,*) a(1:7) would print all seven elements of the array in one row while including the statement in (DO i = 1, 7 WRITE(5,*) a(i) END DO) will write all seven elements of the array in one column in the data file. Both formats will work, but it is the programmers responsibility to be consistent and ensure the data is being read, written correctly. Furthermore, it is highly encouraged that the programmer writes data in column form it is often more convenient, easier to follow, and the plotting software we will use in this class expects this format. All examples provided are given in the recommended column form.

15

Figure 7. This figure demonstrates the use of input and output The above example is a demonstration of data input/output. The variables x, y, z, a, and b are declared as real 11 element arrays. In lines 10-13 array x is set with position values from 0 to 1. Lines 16 21 show variables y and z being set to a period of the sine and cosine functions respectively using the sine and cosine intrinsic functions. Line 16 demonstrates the use of the PRINT statement for displaying strings of text while line 20 demonstrates the use of the print statement to display variable information. Line 24 demonstrates the use of the OPEN statement with a label of 5 and file name of data_set.dat. If this file does not already exist, the open statement will create a .dat file with this name. Lines 27-29 show the variables x, y, and z written to the data file in column form. The file is closed in line 31. Following this is an example of file input from a file that has already been created. For convenience we will use the file we just created. The open statement is called again, this time using label 10 and the same filename is used as before because we want to open the existing file. In lines 36-38 variables a and b read in the first 16

two columns from the data file. If a third array c was included in this list, the third column from the data file would have been read into it. Below is the output from the print statement in line 20.

Figure 8. An example output using the PRINT statement

Appendix A Looping Math and Tricks


Loops are used frequently when coding. Having a good knowledge of what can be done with loops will greatly enhance your ability to get desired results. A few common tricks and techniques are presented here for your reference. COUNTING INTEGERS Counting integers are integer values used to count an action. This may be the number iterations performed in a loop or the number of times a certain condition was met or calculation made. Counting integers are created by initializing some integer value, lets call it counter, to 0 before the loop and then performing the math operation of adding 1 to variable counter every iteration. Figure A1 shows how a simple counting integer might be implemented in a loop. Variable counter is initialized as 0 and incremented by 1 every iteration of the DO WHILE loop. The loop will iterate until counter reaches a value of 12.

Figure A1. A simple counting integer inside of a DO WHILE loop Figure A2 shows how a counting integer might be used in a conditional statement. This technique might be used in situations where the number of times a condition is met during iterations is required. This particular example shows the variable counter to be incremented by 1 every time integer i is evenly divisible by 5. See the Intrinsic Functions section for more information on the MOD function. 17

Figure A2. Counting integer used in a conditional statement SUMMATION LOOPS Frequently loops are used to add up a series of numbers such as in a mathematical series or sequence. This section will discuss how to create a summation loop. A summation loop is essentially a means of adding up a predictable set of numbers in a program using a loop. The counting integer from the previous section is a simple example of a summation loop where an integer value is incremented by 1 each iteration. The same concept may be applied to more complicated problems. Take for example the Eqn A1, (A1) How would we get the value for F in a FORTRAN program? Of course the answer is using a summation loop. Figure A3 shows how the value for F in this mathematical sequence is obtained.

Figure A3. Summation loop used to Another good example for the use of a summation loop is in evaluating integrals. Lets say you are given the function, (A2) What is a good way of evaluating this (or any) integral when writing code? A summation loop is usually a good approach to approximate the solution using the rectangle rule. For those of you who do not remember the rectangle rule it is simply cutting the interval into small sections of width and height F(x), where F(x) is the integrated function evaluated at the midpoint of the interval. Because an integral is essentially the area under a curve, the integral of a function may be approximated by adding up the area of these small rectangles (width x height). The smaller the interval, the more accurate the approximation. 18

The interval is cut into 10 sections giving a of 0.5. The function is evaluated at the midpoint of each of these intervals (0.25, 0.75, 1.25, . etc..). Then the values for F multiplied by are added up for each rectangle.

Figure A4. Numerical integration using the rectangle rule The code presented in Figure A4 produces the result of 36.563. Compared to the exact value of 36.667, this is a pretty good approximation. If the number of rectangles is increased to 100 then the solution of 36.666 is produced showing that smaller intervals can produce more accurate results. Note: More elaborate and accurate numerical integration schemes exist such as trapezoidal, Simpsons rule, and Guassian quadrature. All of these methods utilize a summation loop similar to that presented in this section. PRODUCT LOOP The product loop is another method for performing mathematical operations in coding. It is used to perform a sequential multiplication in coding. For example, lets say that you wanted to multiply a number by 2 seven times. Logically, your first choice should be to multiply that number by 2 to the 7th power, but alternatively you could use a product loop. This example is shown below in Figure A5 for demonstration purposes.

Figure A5. A simple product loop used to multiply a number by 2 multiple times.

19

The product loop may also be used to evaluate a mathematical product. Take, for example, Equation A3 below. It contains a product where the values of and are constant during the multiplication process but
is taken from an array. This calculation is shown in Figure A6. (A3)

Figure A6. Calculation of equation A3 using a product loop First the values for and are initialized using a summation loop based on adding a constant value of 0.25 to the previously indexed value of x which produces values of x = 0, 0.25, 0.5, 0.75 and 1.0. The indices j and m indicate that and are different values from the array x. The value of x from equation A3 is labeled as xx in Figure A6 and given a value of 1.4. The product value is L(j) where j is defined as 1. L(j) is initialized as 1 in order to allow the first product to simply be the first value in the product sequence (think of the process as: y*1 = y y*y = y^2 y^2*y = y^3). If you are observant you might have noticed that L is an array and that we only used the first element in that array. The reason is that this is a practical example, and equation A3 is the cardinal function for polynomial interpolation. To perform the interpolation the cardinal function is evaluated for j = 1, 5 giving all the values for the array L. In short this is an incomplete portion of a code used to interpolate the value at a specified point (in this case x = 1.4) within a set of known values using the Lagrange interpolating polynomial. While polynomial interpolation is not currently covered in this class it is a very useful technique for analyzing data and performing various calculation procedures.

20

Das könnte Ihnen auch gefallen