2. Basic Elements of Fortran -...

27
2. Basic Elements of Fortran

Transcript of 2. Basic Elements of Fortran -...

2. Basic Elements of Fortran

program my_first_program ! Declare variables integer :: i, j, k ! i, j, k are integer ! Interactive input write(*,*) 'Enter the numbers' read(*,*) i, j ! Multiply the numbers k = i*j ! Interactive output write(*,*) 'i*j = ', k stop end program

Structure of a Fortran Program must be in the 1st line if present

declaration section

execution section

termination section

≤ 31 characters

comment after exclamation point

(optional) stop running program, present before end program

tell compiler no more statement

• Click CMD_emacs_Fortran.bat to open command prompt console and Emacs editor

>dir

>mkdir examples

>cd examples

• In Emacs editor, create a new file named 2-2.f90 in the folder \examples

• Copy the program from course webpage and paste on the Emacs editor, and save it.

>gfortran 2-2.f90

>dir

>a.exe

Enter the numbers

2

4

i*j = 8

>a.exe

Enter the numbers

2.

At line 7 of file 2-2.f90 (unit = 5, file = 'stdin')

Fortran runtime error: Bad integer for item 1 in list input

• Goto the folder \GNU_emacs_Fortran

A ~ Z (uppercase) 26

a ~ z (lowercase) 26

0 ~ 9 (numbers) 10

_ (underscore) 1

+ - * / ** (arithmetic symbols) 5

( ) . = , ' $ : ! " % & ; < > ? blank (miscellaneous symbols) 17

Total 86 characters can be used in Fortran 95

• Upper case and lowercase letters are equivalent in Fortran, i.e. Fortran is case insensitive.

• But C++ and Java are case sensitive, i.e., A and a are different characters.

Fortran Character Set

• Executable statement

• Non-executable statement :

provide information necessary for the proper operation of the program

• Free-source form statement (90/95/2003)

• Fixed-source form statement (77 and earlier version)

But backward compatible, i.e., you can use fixed-source form in 90/95, but cannot use free-source form in 77.

Fortran Statement

• Free-source form statement

12 x = y+z ! summation of x and y 12 x = y & +z 12 x = y & & +z 12 x = y & +z

≤ 132 characters

statement number which gives name of a statement to refer to (1~99999)

continuation indicator

≤ 40 lines

syntax error

statement label column

continuation indicator column

instructions column card identification field

• Fixed-source form statement

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 71 72 73 74 75 76 77 78 79 80

1 2 x = y + z

1 2 x = y

1 + Z

Do not use!! Just to show you in case your professor is still using Fortran 77.

A Hollerith card that, when punched, will contain one Fortran statement.

Punching machine

Card reader What computer (IBM 704) looked like when Fortran was introduced.

Fortran coding sheet

Constants and Variables • legal variables:

Time

z01234567

I_LOVE_you

≤ 31 characters; legal characters: a~z, A~Z, 0~9, _

This_is_a_too_long_variable_name (too many characters)

3days (cannot begin with a digit)

money$ (cannot use $)

• illegal variables:

• Fortran has 5 intrinsic (built-in) types of constants and variables:

integer

real

complex

character

logical

• Integer Constant

0 -9999 +18 14

-100. 1,357,076

legal integer constants: illegal integer constants:

• Real Constant

legal real constants: illegal real constants:

10. -99.9 +1.0E-3 (=1 x 10-3) 124.8E20 (=1.248 x 1022) 0.15E+1

1,000,000. 10E3 10.E1.5

• A real or floating-point data : 3.14159265 +1.0E-3 (=1.0 x 10-3) 124.8E20 (=1.248 x 1022) 0.15E+1

mantissa : precision (number of significant digits)

exponent : range

• The precision and range of a real value are determined by number of bits allocated.

(浮點數、尾數)

value = mantissa 2

exponent

• A real or floating-point data is stored in a type of scientific notation of base 2 system consisted of two parts, the mantissa and the exponent:

• Single-precision real number occupies 32 bits (4 bytes) of memory:

24 bits mantissa: ±223 = 8,388,608, i.e., about 6 or 7 significant digits

8 bits exponent: ±27 = 128, 2128 ≅ 3.4 × 1038, 2−128 ≅ 2.9 × 10−39

i.e., range about 10-38 ~ 1038

• Double-precision real number OCCUPIES 64 bits (8 bytes):

53 bits mantissa: ±252 ≈ 4.5 × 1015, i.e., about 14 or 15 significant digits

11 bits exponent: ±210 = 1024, 21024 ≅ 1.8 × 10308, 2−1024 ≅ 5.5 × 10−309

i.e., range about 10-308 ~ 10308

computer bits per default

real number bits in mantissa

precision in decimal digits

bits in exponent range in

exponent

old Intel 32-bit PC (Pentium)

32 24 7 8 10-38 ~ 1038

current Intel 64-bit PC

32 24 7 8 10-38 ~ 1038

declared as double precision

64 53 15 11 10-308 ~ 10308

Cray (supercomputer)

64 49 14 15 10-2465 ~ 102465

'This is a test"

'This is a test''

'This is a test'

"This is a test"

"3.14159265"

"Dog is man's best friend"

'"Who cares? "'

• Character Constants

legal character constants:

illegal constants:

.TRUE.

.FALSE.

(Logical constants are rarely used)

• Logical Constants

integer :: var1, var2, var3 real :: var4, var5 logical :: var6 complex :: var7, var8

optional, but is preferable

num i38

vel q2

Default and Explicit Variables Typing

• Default (not specified): (i,j,k,l,m,n) + other characters are integer variables

• Others are real variables

• The type of a variables can also be explicitly declared by type declaration statements.

• Character variables must be declared by:

character(len=10) :: var1, var2 character(15) :: var3

optional

Assignment Statements and Arithmetic Calculations

i = i+1 If original i is 3, after the assignment statement i is 4

store the value of expression into the variable location

a*-b a*(-b)

a**-2 a**(-2) 2**((8+2)/5) = 2**(10/5) = 2**2 = 4

wrong operation

variable = arithmetic expression

• Arithmetic Operators: + - * / **

• Assignment Statements

i = 3/4 0 is assigned to i 4/4 1 5/4 1 6/4 1 7/4 1 8/4 2 9/4 2

x = 3./4. 0.75 1./3. 0.333333...

On some computer, 3.*(1./3.) ≠ 1

but 2.*(1./2.) = 1

• Integer Arithmetic

• Real Arithmetic (or floating-point arithmetic)

(precision depends on computers)

same as the rules of algebra

distance = 0.5*accel*time**2 = 0.5*accel*(time**2) ≠ (0.5*accel*time)**2 a*b+c*d+e/f**g = (a*b)+(c*d)+(e/(f**g)) a*(b+c)*d+(e/f)**g = (a*(b+c)*d)+(e/f)**g a*(b+c)*(d+e)/f**g = ((a*(b+c))*(d+e))/(f**g) a**b**c = a**(b**c) ≠ (a**b)**c

432 = 49 = 262144 ≠ 642 = 4096

• Hierarchy of Operators (order of arithmetic operators)

• Mixed-mode arithmetic (Do NOT use whenever possible)

The computer converts the integers into real numbers, and real arithmetic is used.

3/2 1

3./2. 1.5

3./2 1.5

3/2. 1.5

1+1/4 1

1.+1/4 1.

1+1./4 1.25

integer (= 0)

real (=0.25)

• Mixed-mode exponentiation

var = y**n = y*y*y*...*y

n times

(This, however, is preferable!)

But

var = y**x = e**(x*LOG(y))

(-2.0)**2 4

(-2.0)**2.0 some compiler will result in runtime error

Intrinsic Functions (some)

Function name & argument Argument type Result type

sqrt(x) SQRT(X) (x ≥ 0) R R

abs(x) R/I R/I

sin(x) (x in radians) R R

cos(x) (x in radians) R R

tan(x) (x in radians) R R

exp(x) R R

alog(x) R R

alog10(x) R R

int(x) integer part of x R I

nint(x) nearest integer to x R I

real(i) I R

fraction(X) = x-int(x) R R

mod(a,b) = a-int(a/b)*b remainder R/I R/I

max(a,b) R/I R/I

min(a,b) R/I R/I

asin(x) R R

acos(x) R R

atan(x) R R

PROGRAM my_first_program ! Purpose: ! To illustrate some of the basic features of a Fortran program. ! Declare the variables used in this program. INTEGER :: i, j, k ! All variables are integers ! Get the variables to multiply together. WRITE(*,*) 'Enter the numbers to multiply: ' READ(*,*) i, j ! Multiply the numbers together. k = i * j ! Write out the result. WRITE(*,*) 'Result = ', k ! Finish up. STOP END PROGRAM

read (io_unit, statement_no_format)

write(io_unit, statement_no_format)

• The types of the variables in the input variable list determine the required format of the input data.

read(*,*) i, j read(*,*) k, l write(*,*) " Output: ", i, j, k, l > 1, 2, 3, 4 > 5, 6, 7 > Output: 1 2 5 6

* means to read from standard input device

* means free-format input (or list-directed input)

begin to read another line of data

List-directed Input and Output

input in console

output in console

• To get the initialized variable as a constant throughout the program, use named constant as:

integer :: i i = 1

integer :: i read(*,*) i

integer :: i = 1

real :: pi pi = acos(-1.)

real :: pi read(*,*) pi

real :: pi = acos(-1.)

real, parameter :: pi = acos(-1.)

real, parameter :: pi = acos(-1.) pi = 3.14

real, parameter :: pi = 3.14 pi = acos(-1.)

These are not allowed since pi has been assigned as a constant parameter.

Initialization of Variables

• 3 ways to initialize a variable:

• Disable the default typing provisions of Fortran.

• If you use implicit none statement, you must explicitly declare EVERY variable in the program otherwise it is considered as an error.

• Good reasons to use implicit none statement: catch typos at compilation time, and make the code more manageable

IMPLICIT NONE Statement

program test_1 real :: time =10.0 write (*,*) 'Time = ', tmie end program test_1

Program test_1 will be compiled successfully, and produce output:

Time = 0.000000E+00.

program test_2 implicit none real :: time =10.0 write (*,*) 'Time = ', tmie end program test_2

In contrast, program test_2 will be compiled with error!

program temp_conversion ! Purpose: To convert an input temperature from degrees ! Fahrenheit to an output temperature in kelvins. implicit none ! Force explicit declaration of variables ! Declare variables, and define each variables when it is declared real :: temp_f ! Temperature in degrees Fahrenheit real :: temp_k ! Temperature in kelvins ! Prompt the user for the input temperature. write(*,*) 'Enter the temperature in degrees Fahrenheit: ' read (*,*) temp_f ! Convert to kelvins. temp_k = (5./9.)*(temp_f-32.)+273.15 ! Write out the result. write(*,*) temp_f, ' degrees Fahrenheit = ', temp_k, ' kelvins ' ! Finish up. end program

15.273329

5 tT

Program Example:

Convert temperature 𝑇𝐹 in degrees of Fahrenheit (°F) to an absolute temperature 𝑡𝑘 in Kelvin (K).

𝑇𝐹 =5

9𝑡𝑘 − 32 + 273.15

• In Emacs editor, create a new file named 2-6.f90 in the folder \examples

• Copy the program from course webpage and paste on the Emacs editor, and save it.

>gfortran 2-6.f90

>dir

>a.exe

Enter the temperature in degrees Fahrenheit:

38.

38.000000 degrees Fahrenheit = 276.48334 kelvins

>

>gfortran 2-6.f90 -o 2-6.out

>dir

>2-6.out

Enter the temperature in degrees Fahrenheit:

80.

80.000000 degrees Fahrenheit = 299.81665 kelvins

>

Exercise 1

Write a Fortran program which prompts to input your name (in English) and ID as in the example program, and output as follow:

My name is your name. My student ID is your id.

Exercise 2

Write a Fortran program to compute the area of a triangle determined by jointing the

three points (x1,y1), (x2,y2) and (x3,y3) given by a user who executes the program.

Use implicit none statement in your program.

Exercise 3

Write a Fortran program to computer the logarithm of a number 𝑥 to an arbitrary base 𝑏,

i.e., log𝑏 𝑥, using the intrinsic function ALOG10(x). Test the program by calculating the

logarithm to the base 𝑒 of number 𝑥 using ALOG(x). Use implicit none statement

in your program.