1 / 150

Introduction to Fortran

Introduction to Fortran. Jon Johansson AICT HPC Workshop April 28, 2008. Downloads. The talk and exercises are available from http://sciviz.aict.ualberta.ca/Fortran/. Agenda. Introduction, history Source format, gfortran Names, Program Structure, Variable Declaration Arrays

raja
Download Presentation

Introduction to Fortran

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Fortran Jon Johansson AICT HPC Workshop April 28, 2008

  2. Downloads • The talk and exercises are available from • http://sciviz.aict.ualberta.ca/Fortran/

  3. Agenda • Introduction, history • Source format, gfortran • Names, Program Structure, Variable Declaration • Arrays • Subprograms/Modules

  4. Why Use Fortran? • “The whole point of compilers, interpreters, layers of abstraction and what-not are to shorten the semantic distance between our intent and the way the computer thinks of things.” • “… it often helps to have a language that makes expressing your intent very clear, concise, and above all, unambiguous.” • Scott Hansellman (computerzen.com)

  5. Why Use Fortran? • from the FORTRAN manual for the IBM 704 (1956), the goal of the FORTRAN creators was a language • “…closely resembling the ordinary language of mathematics …” • “The result should be a considerable reduction in the training required to program, as well as the time consumed in writing programs and eliminating their errors.”

  6. Why Use Fortran? • Fortran was designed from the outset (1954-1957) to do numerical computations • FORmula TRANslator • again, from the IBM 704 (1956) FORTRAN manual: • “The FORTAN language is intended to be capable of expressing any problem of numerical computation. In particular, it deals easily with problems containing large sets of formulae and many variables, …”

  7. What is Fortran written in? Note: the point here is not that one language is “better” than the other. C is more suitable to doing operations that a compiler does, while Fortran is designed for numerical work – trying to write a compiler in Fortran would be hard. You can certainly do numerical work in C if you want to.

  8. Fortran History • Fortran is usually credited with being the first high-level programming language • the first language to use natural language keywords • DO, REAL, INTEGER, … • the first full language to be compiled • necessary because the computer can’t understand the programming language

  9. Fortran History • John W. Backus and a group at IBM started to design the IBM Mathematical Formula Translating System, or Fortran0 in 1954 • the work was completed in 1957 • the authors claimed that the resulting code would be as efficient as handcrafted machine code • it was pretty close

  10. Fortran History • The IBM 704 Data Processing System was a large-scale computer designed for engineering and scientific calculations • Fortran included many features that were specific to the IBM 704, the first computer on which it was implemented http://www.fh-jena.de/~kleine/history/languages/FortranAutomaticCodingSystemForTheIBM704.pdf

  11. Fortran History • "The 704 is the first large-scale, commercially available computer to employ fully automatic floating point arithmetic commands. …” • IBM 704 speed: • multiplies or divides in 240 microseconds • approximately 4,000 operations per second • floating point addition or subtraction operations require 84 microseconds • approximately 12,000 operations per second • 704 memory: • up to 32,768 36-bit words (32 kilo-words)

  12. Fortran Standards • Fortran was the first high level programming language to be standardized • compiler vendors could create compilers that behaved in well defined and consistent ways • programs are much more portable when they don’t depend on vendor specific features

  13. Fortran Standards

  14. Fortran History • Each new version of Fortran adds extensions to the language while retaining compatibility with previous versions • For a long time Fortran was the dominant language of programming in scientific and engineering applications • Now mostly used in High Performance Computing • lots of legacy codes being maintained and developed

  15. Source Code Format • originally Fortran source code was formatted according to rigid rules • different parts of statements had to fall in specific column ranges • since Fortran 90/95 source code formatting is free-form • allows arbitrary use of whitespace to format code

  16. Free Form Source Code • source file with one of the extensions: *.f90, *.f95, [*.hpf], [*.f03] • files with extension in []may be recognized by the compiler, but maybe not - it depends … • a statement line can be up to 132 characters long • ! indicates that the rest of the line is a comment • this can be anywhere • & at the end of a line continues the line

  17. Fixed Form Source Code • source file with one of the extensions *.f, *.f77, [*.for] • columns 1: ‘C’ or ‘*’ start a comment line • columns 1-5: reserved for statement labels • column 6: a character here is used to indicate that a statement has been continued from the previous statement • can use any character except the number zero • columns 7-72: Fortran statements go here • columns 73-80: characters past column 72 are ignored

  18. Fixed Form Source Code • the fixed source format comes from the design of the 704 and the need to use 80 column punch cards • the Hollerith card format: • cards have 12 rows and 80 columns • decimal digits are encoded in rows 0-9 • other characters are encoded using these rows plus rows 11-12 above row 0

  19. Fortran Alphabet • Letters • A B C D E F G H I J K L M N O P Q R S T U V W X Y Z • upper and lower case letters are equivalent • Digits • 0 1 2 3 4 5 6 7 8 9 • Special Characters • space ' " ( ) * + - / : = _ ! & $ ; < > % ? , . [ ] { } ~ ` | # ^ @

  20. Fortran Features • lots of built-in mathematical functions • array operations • operations on array sections • use vector indices • array indices can start and end on arbitrary values • complex numbers as a fundamental data type • complex arithmetic as well, of course

  21. The GNU Fortran Compiler • part of the GNU compiler collection • documentation online at • http://gcc.gnu.org/onlinedocs/gfortran/ • under development since 2000 • still a work in progress • supports most of Fortran 77, 90, 95 and some of 2003

  22. The GNU Fortran Compiler • invoke the compiler with a command of the form gfortran [options] input-file • many of the options are common to gcc with some Fortran specific ones • for example, to compile a program contained in a file named “MyCalc.f90” gfortran –o MyCalc MyCalc.f90 • the ‘–o’ option tells the compiler the name to give the executable

  23. The GNU Fortran Compiler • some useful compiler options -O capital ‘Oh’ • optimize the executable -Onn is an integer from 1 to 3 • the compiler tries to reduce code size and execution time -fbounds-check • check array subscripts against the declared minimum and maximum values -fopenmp • enable the OpenMP extensions

  24. The GNU Fortran Compiler • more useful compiler options -Ldir • add directory dir to the list of directories to be searched for libraries listed with -l -llibrary-name • search the library named library when linking -Idir • Add the directory dir to the head of the list of directories to be searched for header files

  25. Fortran Program Structure • a basic Fortran program looks like this • this is called the “main program unit” • other program units start with the keywords: FUNCTION or SUBROUTINE [program]MyProg declarations processing and I/O end [programMyProg] [ ] denote optional portions. The program name can be included in the end statement only of the program statement is used.

  26. Activity 1 • using a text editor, type the program into a file named “hello.f90” • compile the program • gfortran hello.f90 • run the program • ./a.out program HelloWorld implicit none ! Declare variables ! Do work print *, 'Hello World!' end program HelloWorld

  27. Input/Output • to print something to the computer display Write(*, "(a)")‘This is a string‘ • the ‘a’ is the format specifier for a string • the format string must be inside '(…)' or "(…)"

  28. Input/Output • Fortran programs transfer data to and from external devices during their runs • each device is associated with a Unit Number • the number is often in the range 1 to 99 • the number cannot be negative

  29. Input/Output • to associate an external file with a unit use the OPEN() statement • OPEN(20, FILE=‘output.txt’) • OPEN(21, FILE=‘output.txt’, STATUS = 'NEW' ) • OPEN(22, FILE=‘output.txt’, STATUS = 'NEW‘, ERR = 100, IOSTAT = ErrNum)

  30. Input/Output Open(20,File='outfile.txt', & Status='New') Do i = 1, N If ( i .NE. TestVal(i) ) Then Write(20, "(I15)") i End If End Do Close(20)

  31. Input/Output • Fortran has one function for data input and two for data output • Input: • READ() - transfers input data from external sequential, direct-access, or internal records • Output • PRINT() - displays output on the screen • on some systems TYPE is a synonym for PRINT • WRITE() - transfers output data to external sequential, direct-access, or internal records

  32. Input/Output • The general format of READ and WRITE is • READ(clist) list ! clist == control list • WRITE(clist) list • where the required parts of clist for both READ and WRITE are • [UNIT=] unit-number • [FMT=] format-spec • and other arguments are optional. ! note * refers to default settings READ(*, *) x, y WRITE(*, *) x, y • the first asterisk refers to the default unit number and • the second is the list directed i/o format specifier

  33. Format Specifier • There are 3 ways to give a format specifier: • 1) as an asterisk (*) • the is called list-directed i/o • the format is defined by the computer system at the moment the statement is executed Write(*,*) 'Product = ', x*y

  34. Format Specifier • 2) as a statement label referring to a FORMAT statement containing the specifier between parentheses • this is the Fortran 77 way to do it Write(*, 100) x*y 100 Format('Product = ', f8.2)

  35. Format Specifier • 3) as a character expression whose value commences with a format specification in parentheses • this is what we do in the sample programs Write(*,’(a,f8.2)’) & 'Product = ', x*y Read(*,’(2f8.2)’) x, y

  36. Edit Descriptors • the format specification uses a set of descriptors – here are some common ones • ‘A’ – character string • A20 – the field width is 20 characters • ‘I’ – integers • I9 – integer field is 9 digits wide • ‘F’ – floating point numbers • F9.3 – real field is 9 spaces wide with 3 digits to the right of the decimal point • ‘E’ – real values with exponents • E12.3E2 – real field is 12 spaces wide with 3 digits to the right of the decimal point and 2 digits in the exponent field

  37. Fortran Variable Types • Fortran has five intrinsic variable types • INTEGER: a string of digits with an optional sign • 0, 314, -4502 • REAL: decimal or exponential representation • 3.1416 or 3.1416E0 • DOUBLE PRECISION gives a double length real • COMPLEX: real and imaginary parts of type real • (1.23, -5.56) • LOGICAL: 1 to 4 bytes but only 2 values • .FALSE. or .TRUE. • CHARACTER: characters enclosed in “” or ‘’ • ‘One string’ “Another string”

  38. Variables • variables can be declared using the appropriate data type statement: INTEGER i, j, k REAL radius(100), theta, phi COMPLEX SphericalHarm LOGICAL MoreData CHARACTER(Len=80) TestString

  39. Activity 2 • using a text editor, type the program shown in exercise 2 into a file named “io.f90” • compile the program • gfortran io.f90 • run the program • ./a.out • modify the program to write the product of x and y (the multiplication operator is ‘*’)

  40. Variables • Fortran 90 defines a new syntax for declaring variables. The general form is: TYPE [,attr] :: variable list • where attr is a list of optional Fortran 90 attributes to further define the properties of variables • variables can have attributes such as • Parameter, Save, ALLOCATABLE

  41. Variables • other attributes: • parameter • public • private • target • pointer • intent • optional • the double colon (::) is optional unless ATTRIBUTES or an initialization expression are given • a real 2-d array to allocate later real, allocatable :: x(:,:) • an integer whose value is retained for the next function call int, save :: i

  42. Error Conditions • it is good practice to handle error conditions gracefully if possible • if the program fails with a cryptic error message you’ll have to search to figure it out

  43. Error Conditions • some functions have the following specifiers: • IOSTAT • ERR • for example, the OPEN statement • OPEN(22, FILE=‘output.txt’, STATUS = 'NEW‘, ERR = 100, IOSTAT = ErrNum)

  44. Error Conditions • IOSTAT is an integer variable: = 0 if no error occurs > 0 (the number of the error message) if an error occurs < 0 if an end-of-file record is encountered • ERR is a label to transfer control to if an error condition occurs • OPEN(22, FILE=‘output.txt’, STATUS = 'NEW‘, ERR = 100, IOSTAT = ErrNum)

  45. Activity 3 • using a text editor, make changes to your program from activity 2 as shown in exercise 3 into a file named “io_test.f90” • compile the program • gfortran io_test.f90 • run the program • ./a.out

  46. Variable Representation • variables are basically pointers to some part of memory • the number of bytes is part of the declaration of the variable ( default sizes are frequently 4 bytes)

  47. Variables • DOUBLE PRECISION values have precision greater than the real values on the machine • to declare double precision real and complex variables use: DOUBLE PRECISION theta, phi DOUBLE COMPLEX SphericalHarm • note that DOUBLE COMPLEX isn’t in the standard • might have to use Kinds to get Double Complex

  48. Integer Representation • integers in Fortran are signed • INTEGER lengths can be 1, 2, 4, or 8 bytes • the default INTEGER length is 4 bytes

  49. Floating Point Representation • there are ANSI/IEEE standards to define how floating point numbers are represented and behave in a computer • IEEE Standard 754-1985 • defines binary floating point arithmetic • IEEE Standard 854-1987 • defines decimal floating point arithmetic

  50. Floating Point Representation • given a certain number of bytes allocated to a floating point number, how do we use the bytes to represent the sign, fractional part and the exponent? • for a 4-byte REAL • 8 bits are for the (signed) exponent • 24 bits are for the (signed) mantissa

More Related