Docsity

Fortran 90 Tutorial, Notas de estudo de Engenharia Mecânica

Toggle sidebar
bg1
Fortran 90 Tutorial
Michael Metcalf
CN Division, CERN, CH 1211,Geneva 23, Switzerland
1 Language Elements 1
2 Expressions and Assignments 6
3 Control Statements 8
4 Program Units and Procedures 9
5 Array handling 12
6 Pointers 16
7 Specification Statements 20
8 Intrinsic Procedures 22
9 Input/Output 23
Index 25
Full details of all the items in this tutorial can be found in Fortran 90/95 Explained, by
M. Metcalf and J. Reid, (Oxford, 1996), the book upon which it has been based.
Fortran 90 contains the whole of FORTRAN 77—only the new features are described in
this tutorial.
The tutorial is also available on WWW using the URL
http://wwwcn.cern.ch/asdoc/f90.html
.
The author wishes to thank Michel Goossens (CERN/CN) for his helpful and skilful as-
sistance in preparing this tutorial.
Version of October 1995
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Pré-visualização parcial do texto

Baixe Fortran 90 Tutorial e outras Notas de estudo em PDF para Engenharia Mecânica, somente na Docsity!

Michael Metcalf

CN Division, CERN, CH 1211, Geneva 23, Switzerland

1 Language Elements 1

2 Expressions and Assignments 6

3 Control Statements 8

4 Program Units and Procedures 9

5 Array handling 12

6 Pointers 16

7 Specification Statements 20

8 Intrinsic Procedures 22

9 Input/Output 23

Index 25

Full details of all the items in this tutorial can be found in Fortran 90/95 Explained, by

M. Metcalf and J. Reid, (Oxford, 1996), the book upon which it has been based.

Fortran 90 contains the whole of FORTRAN 77—only the new features are described in

this tutorial.

The tutorial is also available on WWW using the URL

http://wwwcn.cern.ch/asdoc/f90.html.

The author wishes to thank Michel Goossens (CERN/CN) for his helpful and skilful as-

sistance in preparing this tutorial.

Version of October 1995

Fortran has five intrinsic data types. For each there is a corresponding form of literal constant. For the three numeric intrinsic

types they are:

INTEGER

Examples are:

for the default kind ; but we may also define, for instance for a desired range of 104 to 10 4 , a named constant, say two_bytes:

INTEGER, PARAMETER :: two_bytes = SELECTED_INT_KIND(4)

that allows us to define constants of the form

-1234_two_bytes +1_two_bytes

Here, two_bytes is the kind type parameter; it can also be a default integer literal constant, like

-1234_

but use of an explicit literal constant would be non-portable.

The KIND function supplies the value of a kind type parameter:

KIND(1)

KIND(1_two_bytes)

and the RANGE function supplies the actual decimal range (so the user must make the actual mapping to bytes):

RANGE(1_two_bytes)

Also, in DATA statements, binary, octal and hexadecimal constants may be used:

B'01010101'
O'01234567'

Z'10fa'

REAL

There are at least two real kinds – the default, and one with greater precision (this replaces DOUBLE PRECISION). We might

specify

INTEGER, PARAMETER :: long = SELECTED_REAL_KIND(9, 99)

for at least 9 decimal digits of precision and a range of 10 ^99 to 10 99 , allowing

1.7_long

Also, we have the intrinsic functions

KIND(1.7_long) PRECISION(1.7_long) RANGE(1.7_long)

that give in turn the kind type value, the actual precision (here at least 9), and the actual range (here at least 99).

COMPLEX

This data type is built of two integer or real components:

(1, 3.7_long)

The numeric types are based on model numbers with associated inquiry functions (whose values are independent of the values

of their arguments). These functions are important for writing portable numerical software.

DIGITS(X) Number of significant digits

EPSILON(X) Almost negligible compared to one (real)

HUGE(X) Largest number

MAXEXPONENT(X) Maximum model exponent (real)

MINEXPONENT(X) Minimum model exponent (real)

PRECISION(X) Decimal precision (real, complex)

RADIX(X) Base of the model

RANGE(X) Decimal exponent range

TINY(X) Smallest postive number (real)

The forms of literal constants for the two non-numeric data types are:

CHARACTER

'A string' "Another" 'A "quote"' ''

(the last being a null string). Other kinds are allowed, especially for support of non-European languages:

2_' '

and again the kind value is given by the KIND function:

KIND('ASCII')
LOGICAL

Here, there may also be different kinds (to allow for packing into bits):

.FALSE.

.true._one_bit

and the KIND function operates as expected:

KIND(.TRUE.)

We can specify scalar variables corresponding to the five intrinsic types:

INTEGER(KIND=2) i REAL(KIND=long) a COMPLEX current LOGICAL Pravda CHARACTER(LEN=20) word CHARACTER(LEN=2, KIND=Kanji) kanji_word

where the optional KIND parameter specifies a non-default kind, and the LEN= specifier replaces the *len form. The explicit

KIND and LEN specifiers are optional and the following works just as well:

CHARACTER(2, Kanji) kanji_word

For derived-data types we must first define the form of the type:

TYPE person CHARACTER(10) name REAL age END TYPE person

and then create structures of that type:

TYPE(person) you, me

To select components of a derived type, we use the % qualifier:

you%age

and the form of a literal constant of a derived type is shown by:

you = person('Smith', 23.5)

which is known as a structure constructor.

There are some other interesting character extensions. Just as a substring as in

CHARACTER(80), DIMENSION(60) :: page ... = page(j)(i:i)! substring

was already possible, so now are the substrings

'0123456789'(i:i) you%name(1:2)

Also, zero-length strings are allowed:

page(j)(i:i-1)! zero-length string

Finally, there are some new intrinsic character functions:

ACHAR IACHAR (for ASCII set) ADJUSTL ADJUSTR LEN_TRIM INDEX(s1, s2, BACK=.TRUE.) REPEAT SCAN (for one of a set) TRIM VERIFY(for all of a set)

2. Expressions and Assignments

The rules for scalar numeric expresions and assignments, as known from FORTRAN 77, are extended to accommodate the

non-default kinds we encountered in chapter 1. Thus, the mixed-mode numeric expression and assignment rules incorporate

different kind type parameters in an expected way:

real2 = integer + real

converts integer to a real value of the same kind as real1; the result is of same kind, and is converted to the kind of real2 for

assignment.

For scalar relational operations, there is a set of new, alternative operators:

so we can write expressions such as

IF (a < b .AND. i /= j) THEN! for numeric variables flag = a == b! for logical variable flag

In the case of scalar characters , two old restrictions are lifted. Given

CHARACTER(8) result

it is now legal to write

result(3:5) = result(1:3)! overlap allowed result(3:3) = result(3:2)! no assignment of null string

For an operation between derived-data types, or between a derived type and an intrinsic type, we must define the meaning of

the operator. (Between intrinsic types, there are intrinsic operations only.) Given

TYPE string INTEGER length CHARACTER(80) value END TYPE string CHARACTER char1, char2, char TYPE(string) str1, str2, str

we can write

str3 = str1//str2! must define operation str3 = str1.concat.str 2! must dedine operation char3 = char2//char3! intrinsic operator only str3 = char1! must define assignment

For the first three cases, assignment applies on a component-by-component basis (but can be overridden), and the first two cases

require us to define the exact meaning of the // symbol. We see here the use both of an intrinsic symbol and of a named operator,

.concat.. A difference is that, for an intrinsic operator token, the usual precedence rules apply, whereas for named operators

their precedence is the highest as a unary operator or the lowest as a binary one. In

vector3 = matrix * vector1 + vector vector3 =(matrix .times. vector1) + vector

the two expresions are equivalent only if appropriate parentheses are added as shown. In each case, we have to provide, in a

module, procedures defining the operator and assignment, and make the association by an interface block, also in the module

(we shall return to this later).

3. Control Statements

The CASE construct is a replcement for the computed GOTO, but is better structured and does not require the use of statement

labels:

SELECT CASE (number)! NUMBER of type integer CASE (:-1)! all values below 0 n_sign = - CASE (0)! only 0 n_sign = 0 CASE (1:)! all values above 0 n_sign = 1 END SELECT

Each CASE selector list may contain a list and/or range of integers, character or logical constants, whose values may not overlap

within or between selectors:

CASE (1, 2, 7, 10:17, 23)

A default is available:

CASE DEFAULT

There is only one evaluation, and only one match.

A simplified but sufficient form of the DO construct is illustrated by

outer: DO inner: DO i = j, k, l! only integers : IF (...) CYCLE : IF (...) EXIT outer END DO inner END DO outer

where we note that loops may be named so that the EXIT and CYCLE statements may specify which loop is meant.

Many, but not all, simple loops can be replaced by array expressions and assignments, or by new intrinsic functions. For instance

tot = 0. DO i = m, n tot = tot + a(i) END DO

becomes simply

tot = SUM( a(m:n) )

4. Program Units and Procedures

In order to discuss this topic we need some definitions. In logical terms, an executable program consists of one main program

and zero or more subprograms (or procedures ) - these do something. Subprograms are either functions or subroutines , which

are either external, internal or module subroutines. (External subroutines are what we know from FORTRAN 77.)

From an organizational point of view, however, a complete program consists of program units. These are either main programs,

external subprograms or modules and can be separately compiled.

An internal subprogram is one contained in another (at a maximum of one level of nesting) and provides a replacement for the

statement function:

SUBROUTINE outer REAL x, y : CONTAINS SUBROUTINE inner REAL y y = x + 1. : END SUBROUTINE inner! SUBROUTINE mandatory END SUBROUTINE outer

We say that outer is the host of inner, and that inner obtains access to entities in outer by host association (e.g. to x), whereas

y is a local variable to inner. The scope of a named entity is a scoping unit , here outer less inner, and inner.

The names of program units and external procedures are global , and the names of implied-DO variables have a scope of the

statement that contains them.

Modules are used to package

 global data (replaces COMMON and BLOCK DATA);

 type definitions (themselves a scoping unit);

 subprograms (which among other things replaces the use of ENTRY);

 interface blocks (another scoping unit, see next article);

 namelist groups.

An example of a module containing a type defition, interface block and function subprogram is:

MODULE interval_arithmetic TYPE interval REAL lower, upper END TYPE interval INTERFACE OPERATOR(+) MODULE PROCEDURE add_intervals END INTERFACE : CONTAINS FUNCTION add_intervals(a,b) TYPE(interval), INTENT(IN) :: a, b TYPE(interval) add_intervals add_intervals%lower = a%lower + b%lower add_intervals%upper = a%upper + b%upper END FUNCTION add_intervals! FUNCTION mandatory : END MODULE interval_arithmetic

and the simple statement

USE interval_arithmetic

provides use association to all the module’s entities. Module subprograms may, in turn, contain internal subprograms.

Overloading and generic interfaces

Interface blocks provide the mechanism by which we are able to define generic names for specific procedures:

INTERFACE gamma! generic name FUNCTION sgamma(X)! specific name for low precision REAL (SELECTED_REAL_KIND( 6)) sgamma, x END FUNCTION dgamma(X)! specific name for high precision REAL (SELECTED_REAL_KIND(12)) dgamma, x END END INTERFACE

where a given set of specific names corresponding to a generic name must all be of functions or all of subroutines.

We can use existing names, e.g. SIN, and the compiler sorts out the correct association.

We have already seen the use of interface blocks for defined operators and assignment (see Part 2).

Recursion

Indirect recursion is useful for multi-dimensional integration. To calculate

volume = integrate(fy, ybounds)

we might have

RECURSIVE FUNCTION integrate(f, bounds) ! Integrate f(x) from bounds(1) to bounds(2) REAL integrate INTERFACE FUNCTION f(x) REAL f, x END FUNCTION f END INTERFACE REAL, DIMENSION(2), INTENT(IN) :: bounds : END FUNCTION integrate

and to integrate f(x, y) over a rectangle

FUNCTION fy(y) USE func! module func contains function f REAL fy, y yval = y fy = integrate(f, xbounds) END

Direct recursion is when a procedure calls itself, as in

RECURSIVE FUNCTION factorial(n) RESULT(res) INTEGER res, n IF(n.EQ.1) THEN res = 1 ELSE res = n*factorial(n-1) END IF END

Here, we note the RESULT clause and termination test.

5. Array handling

Array handling is included in Fortran 90 for two main reasons:

 the notational convenience it provides, bringing the code closer to the underlying mathematical form;

 for the additional optimization opportunities it gives compilers (although there are plenty of opportunities for degrading

optimization too!).

At the same time, major extensions of the functionality in this area have been added.

We have already met whole arrays in Parts 1 and 2—here we develop the theme.

Zero-sized arrays

A zero-sized array is handled by Fortran 90 as a legitimate object, without special coding by the programmer. Thus, in

DO i = 1,n x(i) = b(i) / a(i, i) b(i+1:n) = b(i+1:n) - a(i+1:n, i) * x(i) END DO

no special code is required for the final iteration where i = n.

We note that a zero-sized array is regarded as being defined; however, an array of shape, say, (0,2) is not conformable with one

of shape (0,3), whereas

x(1:0) = 3

is a valid “do nothing” statement.

Assumed-shape arrays

These are an extension and replacement for assumed-size arrays. Given an actual argument like:

REAL, DIMENSION(0:10, 0:20) :: a : CALL sub(a)

the corresponding dummy argument specification defines only the type and rank of the array, not its size. This information has

to be made available by an explicit interface, often using an interface block (see part 4). Thus we write just

SUBROUTINE sub(da) REAL, DIMENSION(:, :) :: da

and this is as if da were dimensioned (11,21). However, we can specify any lower bound and the array maps accordingly. The

shape, not bounds, is passed, where the default lower bound is 1 and the default upper bound is the corresponding extent.

Automatic arrays

A partial replacement for the uses to which EQUIVALENCE is put is provided by this facility, useful for local, temporary arrays,

as in

SUBROUTINE swap(a, b) REAL, DIMENSION(:) :: a, b REAL, DIMENSION(SIZE(a)) :: work! array created on a stack work = a a = b b = work END SUBROUTINE swap

Array elements

Simple case: given REAL, DIMENSION(100, 100) :: a

we can reference a single element of a as, for instance, a(1, 1). For a derived data type like

TYPE triplet REAL u REAL, DIMENSION(3) :: du END TYPE triplet

we can declare an array of that type:

TYPE(triplet), DIMENSION(10, 20) :: tar

and a reference like

tar(n, 2)

is an element (a scalar!) of type triplet, but

tar(n, 2)%du

is an array of type real, and

tar(n, 2)%du(2)

is an element of it. The basic rule to remember is that an array element always has a subscript or subscripts qualifying at least

the last name.

Array subobjects (sections)

The general form of subscript for an array section is

[lower ] : [upper ] [:stride ]

as in

REAL a(10, 10) a(i, 1:n)! part of one row a(1:m, j)! part of one column a(i, : )! whole row a(i, 1:n:3)! every third element of row a(i, 10:1:-1)! row in reverse order a( (/ 1, 7, 3, 2 /), 1)! vector subscript a(1, 2:11:2)! 11 is legal as not referenced a(:, 1:7)! rank two section

Note that a vector subscript with duplicate values cannot appear on the left-hand side of an assignment as it would be ambiguous.

Thus,

b( (/ 1, 7, 3, 7 /) ) = (/ 1, 2, 3, 4 /)

is illegal. Also, a section with a vector subscript must not be supplied as an actual argument to an OUT or INOUT dummy argu-

ment.

Arrays of arrays are not allowed:

tar%du! illegal

We note that a given value in an array can be referenced both as an element and as a section:

a(1, 1)! scalar (rank zero) a(1:1, 1)! array section (rank one)

depending on the circumstances or requirements.

By qualifying objects of derived type, we obtain elements or sections depending on the rule stated earlier:

tar%u! array section (structure component) tar(1, 1)%u! component of an array element

Arrays intrinsic functions

Vector and matrix multiply

DOT_PRODUCT Dot product of 2 rank-one arrays MATMUL Matrix multiplication

Array reduction

ALL True if all values are true ANY True if any value is true. Example: IF (ANY( a > b)) THEN COUNT Number of true elements in array MAXVAL Maximum value in an array MINVAL Minimum value in an array PRODUCT Product of array elements SUM Sum of array elements

Array inquiry

ALLOCATED Array allocation status LBOUND Lower dimension bounds of an array SHAPE Shape of an array (or scalar) SIZE Total number of elements in an array UBOUND Upper dimension bounds of an array

Array construction

MERGE Merge under mask PACK Pack an array into an array of rank SPREAD Replicate array by adding a dimension UNPACK Unpack an array of rank one into an array under mask

Array reshape

RESHAPE Reshape an array

Array manipulation

CSHIFT Circular shift EOSHIFT End-off shift TRANSPOSE Transpose of an array of rank two

Array location

MAXLOC Location of first maximum value in an array MINLOC Location of first minimum value in an array

Association

A pointer’s association status is one of

 undefined (initial state);

 associated (after allocation or a pointer assignment);

 disassociated:

DEALLOCATE (p, q)! for returning storage NULLIFY (p, q)! for setting to 'null'

Some care has to be taken not to leave a pointer “dangling” by use of DEALLOCATE on its target without NULLIFYing any other

pointer referring to it.

The intrinsic function ASSOCIATED can test the association status of a defined pointer:

IF (ASSOCIATED(pointer)) THEN

or between a defined pointer and a defined target (which may, itself, be a pointer):

IF (ASSOCIATED(pointer, target)) THEN

Pointers in expressions and assignments

For intrinsic types we can “sweep” pointers over different sets of target data using the same code without any data movement.

Given the matrix manipulation y = B C z, we can write the following code (although, in this case, the same result could be

achieved more simply by other means):

REAL, TARGET :: b(10,10), c(10,10), r(10), s(10, z(10) REAL, POINTER :: a(:,:), x(:), y(:) INTEGER mult : DO mult = 1, 2 IF (mult == 1) THEN y => r! no data movement a => c x => z ELSE y => s! no data movement a => b x => r END IF y = MATMUL(a, x)! common calculation END DO

For objects of derived data type we have to distinguish between pointer and normal assignment. In

TYPE(entry), POINTER :: first, current : first => current

the assignment causes first to point at current, whereas

first = current

causes current to overwrite first and is equivalent to

first%value = current%value first%index = current%index first%next => current%next

Pointer arguments

If an actual argument is a pointer then, if the dummy argument is also a pointer,

 it must have same rank,

 it receives its association status from the actual argument,

 it returns its final association status to the actual argument (note: the target may be undefined!),

 it may not have the INTENT attribute (it would be ambiguous),

 it requires an interface block.

If the dummy argument is not a pointer, it becomes associated with the target of the actual argument:

REAL, POINTER :: a(:,:) : ALLOCATE (a(80, 80)) : CALL sub(a) : SUBROUTINE sub(c) REAL c(:, :)

Pointer functions

Function results may also have the POINTER attribute; this is useful if the result size depends on calculations performed in the

function, as in

USE data_handler REAL x(100) REAL, POINTER :: y(:) : y => compact(x)

where the module data_handler contains

FUNCTION compact(x) REAL, POINTER :: compact(:) REAL x(:) ! A procedure to remove duplicates from the array x INTEGER n :! Find the number of distinct values, n ALLOCATE(compact(n)) :! Copy the distinct values into compact END FUNCTION compact

The result can be used in an expression (but must be associated with a defined target).

Arrays of pointers

These do not exist as such: given

TYPE(entry) :: rows(n)

then

rows%next! illegal

would be such an object, but with an irregular storage pattern. For this reason they are not allowed. However, we can achieve

the same effect by defining a derived data type with a pointer as its sole component: