FORTRAN – FORmula TRANlastion

advertisement
1
Lecture 3
Type Statements
 Type statements define a variable to be a specific type (REAL,
INTEGER, etc.). General format is:
type specifier :: list
where type specifier is REAL, INTEGER, COMPLEX or CHARACTER
list is a list of variable (or array) names separated by commas
 Examples:
INTEGER :: A, I, C
integer :: A, I, c
makes variables A, I and C integers
makes variables A, I and C integers
(remember Fortran ignores case)
REAL :: Box, K
makes variables Box and K real
 Character type statements usually define the length of the character
string. Valid expressions are:
CHARACTER(10)::Title
Title can store 10 characters
CHARACTER(len=10) :: Title
Title can store 10 characters
CHARACTER::Title*10
Title can store 10 characters
2
Lecture 3
Named Constants – Parameter attributes
Variable names may be assigned a value which cannot be changed
during execution. They are useful when you want to refer to a constant
by a name. The general format is
type-specifier, PARAMETER :: list
where list is a list of variables set equal to a value. For example,
REAL, PARAMETER :: Alpha=12.2E-6, PI=3.141593
In the above, the name PI can be used like a variable name in an
expression but its value can never be changed. The value is assigned at
compile time.
In Fortran IV and 77, this was called a DATA statement and its form was
DATA A, PI /2.3, 3.141593/
3
Lecture 3
Variable Initialization
In Fortran, all variables are initially undefined! Variables may be
typed and initialized to a value at compile time by assigning a value in
the type statement. The general form is
type-specifier :: variable=value
The variable type and value must agree. Examples include:
REAL :: A=0.0, I=5, Area=14.3E+27
The values of initialized variables may change during execution (in
direct contrast to a PARAMETER which cannot change).
4
Lecture 3
A word about spacing in Fortran statements. In most cases, blank
spaces in Fortran statements are ignored, i.e., treated just as if the blank
spaces were not there. Thus, the following are treated equivalently:
REAL :: A,B,C
REAL :: A,
B,
C
So, use spacing in writing Fortran instructions to make the statements
easy to read.
The exception is in character strings where a blank space is a valid
character:
CHARACTER(2), PARAMETER :: Units=’cm’
CHARACTER(9), PARAMETER :: title=’answer is’
In the last statement, the blank between “answer” and “is” is counted in
the total number of characters (9).
5
Lecture 3
Implicit Typing of Variables and IMPLICIT NONE
 In Fortran, any variables that begin with the letters I (or i), J, K, L, M
or N are implicitly assumed to be INTEGER type. All the remaining
letters are implicitly REAL.
I, J, K, L, M, N, i, ii, ijk, i2, I2,
IXX, Ixx, IYY, Jack, Mass  all implicitly integer
A, AI, aii, box, Velocity
 all implicitly real
 If you want to override the implicit typing of variables, you must use
the statement
IMPLICIT NONE
Once you use the IMPLICIT NONE statement, all variables and
names of functions must be explicitly typed with a TYPE statement.
Lecture 3
Operations with Variables and/or Constants
Numeric operations for Real, Integer and Complex variables and/or
constants are given by:
+
addition
subtraction
/
division
**
exponentiation
Example: B**C + C**2 - 2.0 +D*E/F
Same-Mode Operations
Same mode operations occur between two variables and/or constants of
the same type. The operation produces a result consistent with the
variables connected by the operator.
9.0/4.0
yields the real result 2.25
9.0*4.0
yields the real result 36.0
2.0**3
yields the real result 8.0 (sort of an exception to rule)
6
7
Lecture 3
But be careful about integer division. The result of an integer divided
by an integer is always equal to the integer obtain by truncating the result
to the next lowest integer if there is a remainder.
6/2
6/3
6/4
6/5
6/6
6/7
6/12
yields the integer
yields the integer
yields the integer
yields the integer
yields the integer
yields the integer
yields the integer
3
2
1
1
1
0
0
8
Lecture 3
Mixed-Mode Expressions
To evaluate an operation between a real and integer quantity, the integer
is first converted to real, the operation performed, and the result is real.
1/4.0
is treated as
1.0/4.0
and yields
0.25
Exponentiation is the only exception.
2.0**3
is done as
2.0*2.0*2.0
and yields
8.0
NOTE: you can do 2.0**3.0 but the operation is done approximately
using a series approximation. The result will not usually be as accurate
because of round-off in real arithmetic.
9
Lecture 3
Priority Rules for Evaluating Arithmetic Expressions
Done First:
Exponentiation. Consecutive exponentiations done right
to left.
Done Second: Multiplication and Division. Done as they appear in the
expression left to right.
Done Third:
Addition and Subtraction. Done as they appear in the
expression left to right.
2**3**2 = 2**9 = 512
2 + 4**2/3 = 2 + 16/3 = 2 + 5 = 7
3 + 8/5 * 5 = 3 + 1 * 5 = 8
Parenthesis may be used to over-ride the default priority. Expressions in
parenthesis are evaluated first. Parenthesis may be nested. Inner-most
parenthesis is done first.
(2**3)**2 = 8**2 = 64
3 + 8/5*5 = 3 + 1*5 = 8
3 + 8/(5*5) = 3 + 8/25 = 3 + 0 = 3
10
Lecture 3
Intrinsic Functions
A number of intrinsic numeric functions are included for common
operations. Some of these are:
SQRT(real argument)
ABS (real argument)
REAL (integer argument)
SIN (real argument)
TAN (angle)
EXP (x)
LOG (x)
ASIN (x)
ACOS (x)
ATAN(X)
ATAN2(Y,X)
 Y
X
square root (real result)
absolute value (real result)
converts integer to real
sine of angle in radians
tangent of angle in radians
exponential function
natural log
arc sine, result is  /2   /2
arc cosine, 0  
arc tangent,  /2   /2
arc tangent,   
See more in Table 2-2 and pp. 270-278.
11
Lecture 3
Assignment Statements
The general form of an assignment statement is
variable = expression
The expression is evaluated and the result is assigned to the memory
location called variable. If the expression is of a different type then
variable, it is converted to the same type as variable before being
assigned to variable (for REAL, INTEGER and COMPLEX only).
A = B + 2.0
I = B + 2.0
I=I+2
looks up value of B, adds 2.0,
and assigns result to A
looks up values of B, adds 2.0,
converts result to an integer, and
stores (assigns) this integer to I
looks up value stored in I, adds 2,
and stores result into I.
12
Lecture 3
A = C + SQRT (x**2+y**2)
A = C + (x**2+y**2)**(0.5)
this and next statement are
equivalent
Consider the following sequence of statements being executed:
A = 2.0
B = 9.0
C = A + SQRT (B)
A = A + SQRT (B)
E=A+C
stores 2.0 into A (assigns 2.0 to A)
stores 9.0
results in C being assigned the value 5.0
results in A being assigned the value 5.0
results in E being assigned the value 10.0
Lecture 3
13
Numerical Precision and limits on numbers
All numbers are stored in binary form. Before a number that is input into
a computer program (in base 10) can be used by the computer, it must be
converted to binary. Likewise, before a number in memory can be
displayed so you can read it, it must be converted from binary back to
base 10. Depending upon the computer and type of variable, variables
may be represented by anywhere from 8 bits, 16 bits, 32 bits, 64 bits, 128
bits, and larger (in rare cases). The number of bits used to represent a
variable or constant will affect the inherent round-off that constants
occurs in evaluating expressions.
Standard “Single Precision” uses 32 bits for integers and real numbers.
This is often referred to as a 32 bit word.
Integers have exact values because the conversion from binary to base 10
is exact. A 32 bit integer uses 1 bit for the sign and 31 bits for the
number. Thus, the largest single precision integer is 231-1.
Lecture 3
14
Real numbers are approximate because only a portion of a 32 bit storage
location is used to represent the mantissa (or decimal part) of the
number. Consider a real number being represented as 0. xxxxxxxE  nn
where xxxxxxx is the mantissa. In binary, the approximate scheme to
store a real number is: 1 bit for sign of number, 23 bits for xxxxxxx, 1 bit
for sign of exponent, and 7 bits for the exponent nn. This gives an
accuracy of approximately 7.2 digits precision (for the mantissa) and an
exponent which can have the range of –75 to +77. This vary slightly by
computer.
Standard “Double Precision” for real numbers uses 64 bit storage
locations (word length is 64 bits), and provides roughly 16-digit
precision.
Many hand-held calculators use a word length that provides roughly
12-digit precision for real numbers. Consequently, if you compare a
long series of calculations done on a computer in single precision with
the results from a hand-held calculator, you may find slightly different
results due to the different round-off errors in the two.
15
Lecture 3
Basic Input and Output
There are two types of output statements
 List-directed (some times called free-field or free-formated)
 Formatted
The general forms of list-directed output are:
PRINT *, output-list
WRITE (*,*) output-list
where
output-list is a list of variables separated by commas
to be output to the computer terminal.
The variables may be any type including
character.
Note: There is a comma before the output-list in PRINT * but not before
the output-list in WRITE (*,*) !!!
Lecture 3
16
Some examples:
PRINT *, “The cost is equal to “, Cost
WRITE (*,*) ‘for I = ‘, I, ‘
x,y,a are equal to ‘, X, Y, A
PRINT *
note: no comma  prints a blank line
 Each execution of a PRINT or WRITE statement produces a new line
of output.
 If the output will not fit on one line, a next line is started.
 Real numbers are printed in decimal format or exponent format
depending on the magnitude of the number.
 The * is what is telling the computer to use no specific format in
outputting the values.
 You have absolutely NO control of what the output is going to look
like in regard to spacing and formatting.
17
Lecture 3
The general forms of list-directed input are:
READ *, input-list
READ (*,*) input-list
where
input-list is a list of values separated by commas to
be input via the computer keyboard. The
variables may be any type including
character.
READ *, Initial_Velocity
READ (*,*) Initial_Velocity
CHARACTER (1):: Answer
READ *, X, Y, A, Answer
expects 1 integer value
expects 1 integer value
expects one character
expects 3 real values and 1
character string (in that order)
 The input supplied (i.e., entered with the keyboard) must match
EXACTLY in TYPE with the variable type and in the SAME order.
Lecture 3
18
 The number of values supplied must be EXACTLY what is requested
by the READ statement.
 Real numbers may be input in decimal or exponent form.
 Value and character input may be separated by either
 one or more blank spaces, or
 a comma
 CHARACTER input is supplied WITHOUT the quotes. The number
of characters input must match EXACTLY with the length of the
CHARACTER variable.
CHARACTER(3)::Answer
READ *, Answer
must input 3 characters (without
any quotes)
 The * is what is telling the computer to use no specific format in
inputting the values.
 If you provide fewer values than the input-list asks before prior to
hitting the Enter key on the keyboard, this will be considered an error
because the entire list has not been full-filled.
19
Lecture 3
When a READ statement is executed, the computer stops and waits for
you input via the terminal. The computer does not automatically print
out any information as to what values that it is expecting (nor will you
know what the computer is expecting as input). Therefore, you must do
that with a PRINT statement prior to the READ statement. For example,
PRINT *, “Input the span of the wing:”
READ *, Wing_Span
20
Lecture 3
Program Layout
The typical layout of a Fortran program will be:
PROGRAM header
specification part
execution part
END statement
statements used only at compile time
statements executed during execution
All programs must begin with a program header called a PROGRAM
statement and must end with an END statement. The compiler uses this
to keep track of different programs (and subroutines and functions) when
more that one program element is utilized. The general form of the
PROGRAM statement is
PROGRAM name
where name is the name you assign to the program. name must follow
the same rules as a variable name and must be unique.
21
Lecture 3
The END statement is simply written as
END
or
END PROGRAM
The specification part includes statements like
REAL::
REAL, PARAMETER::
IMPLICIT NONE
etc.
and are those statements which are used by the compiler during
compilation to define variable types, allocate memory, etc. They are
termed non-executable statements since they are not executed but only
used by the compiler. There are other specification types we will discuss
later (like DIMENSION).
The execution part includes all of the executable statements that are part
of the algorithm for your program.
22
Lecture 3
Execution of the executable statements can be halted with a STOP
statement of the form:
STOP
or
STOP constant
where constant is an integer constant or a character that will be displayed
when the STOP is executed. Some compilers require a STOP statement;
some don’t. Those that don’t will stop when the END statement is
reached.
Program Format
The main rules for program format (i.e., how you enter or type it) are:
1. A line may have a maximum of 132 characters.
2. An ampersand (&) must be placed at the end of a line if it is to be
continued on the next line. Maximum of 39 continuation lines.
Alternately, for fixed format compilers, any non-blank character may
Lecture 3
23
be placed in column 6 of the continued line to indicate that it
continues from the previous line.
3. A line may contain more than one statement, provided the
statements are separated by semicolons. Don’t do this – makes it
hard to read!
4. Any characters following an exclamation point (!) are considered
comments and not compiled. The comment may be placed after an
executable statement (on the same line). In fixed format compilers, a
comment line is indicated by placing a C in column 1.
5. If a statement requires a statement label, this label must precede the
statement and must be separated from it by a least one blank space.
Statement labels must be in the range 1 to 99999. In fixed format
compilers, the statement must be placed in columns 1 to 5.
A sample program is listed below. See the text for many other examples.
24
Lecture 3
1
7
1
0
2
0
3
0
4
0
5
0
6
0
PROGRAM Main
! This program calculates factorials of any number N from 1 to 19
CHARACTER (1)::ans
INTEGER::n,i,nfact
10 PRINT *, "Enter the value of N:"
READ *, n
OPEN (unit=10,file='factorial.dat')
IF (n.lt.20) THEN
nfact=1
DO i=1,n
nfact=nfact*i
END DO
PRINT *, "N =", n, "
N factorial =",nfact
PRINT *, "do you wish to do another case? Enter Y or N."
WRITE (10,50) n,nfact
50 FORMAT (5x,"N = ", I2, " N factorial = ",I12)
READ *,ans
IF (ans.eq."Y") go to 10
STOP
ELSE
PRINT *, "N must be less than 20. Try again."
GO TO 10
END IF
END
Download