Computational Physics - Fortran 90

Document Sample
Computational Physics - Fortran 90 Powered By Docstoc
					Computational Physics - Fortran 90                                                                                                                                        25 February 1997




              Fortran 90                 Decision Structures
                                                                                                    Fortran 90              Decision Structures
                      •     IF commands 3 main possibilities                                        (a) Logical expressions. :
                            • IF (logical expression) Execution statements
                                                                                                        • evaluate whether expression is true or false
                                                                                                          •     Decisions are made by testing the truth of logical expressions.
                            •      IF (logical expression) THEN
                                                                             expression TRUE
                                                                                                          –     e.g if x > 0 then do this
                                        Execution statements
                                   ELSE                                                             –     Relational logical expressions:         most common type

                                       Execution statements                  expression FALSE             –     Compare the values of arithmetic or character expressions.
                                   END IF                                                                 –     Relational operators:      <      <=     ==      /=     >= >
                                                                                                          –     FORTRAN 77 versions: .LT. .LE. .EQ. .NE. .GE. .GT.
                            •      IF (logical expression) THEN
                                       Execution statements                                               –     e.g. b2 < 4ac              b*b < 4.*a*c
                                                                                                                     I = J                 I == J
                                   ELSE IF (logical expression) THEN
                                                                                                                     temp ≥ 100            temp >= 100
                                       Execution statements                                                          (I + J)(I + K) ≠ L     (I + J)*(I + K) /= L
                                   END IF                                                                            Answer = Yes          Answer == "Yes"
            Fortran 90 Lecture 4                         AS 3013                                1   Fortran 90 Lecture 4                     AS 3013                              2




            Decision Structures: Tips                                                               Decision Structures, Logical Expressions (cont.)

            • Evaluation of expression gives result either                                          • To combine logical expressions: Use .OR. .AND. .NOT.
                              TRUE or FALSE.                                                              – IF ((x < y) .AND. ( y < z)) THEN
                  – if INTEGER       I == J integers held exactly in memory.
                  – if REAL/DOUBLE PRECISION            A == B ??                                   • LOGICAL type variables;
                    Real numbers are not held with complete accuracy.                                 LOGICAL constants are .TRUE. .FALSE.
                    Never use == or /= to compare real expressions.
                                                                                                       – IF ( keep_going) THEN

                  – Instead use: IF(ABS(A-B) < Tolerance)
                         to test for 'equality'.                                                    • INDENT
                            Tolerance defined as small (Tolerance = 1.e-4)                                – It is good programming practice to indent the body of an IF
                                                                                                            structure, the IF-block, by a few spaces to identify the block and
                  – Recommended: Spaces to make expressions more readable.                                  improve readability of the code.
                  –              Same data type on each side of operator.

            Fortran 90 Lecture 4                         AS 3013                                3   Fortran 90 Lecture 4                     AS 3013                              4




Lecture 4                                                                                                                                                                               1
Computational Physics - Fortran 90                                                                                                                                   25 February 1997




               Decision Structures (cont.)                                                    Decision Structures, Control Statements(cont.)

               (b) Control Statements                                                         • Alternate processing when logical expression FALSE.
                      – Algorithm:     if logical expression true                                   – Algorithm:     if logical expression true
                                            then processing statement                                                     then processing statement A
               • Logical Block IF structure                                                                               else processing statement B
                      – IF (logical expression) THEN                                          • ELSE statement
                                      ↓ true                                                        – IF (logical expression) THEN
                                  IF-block                                                                          ↓ true
                        false    executable statements  body                                              false     processing statement A              IF-block
                                  processing statements                                               ELSE
                                      ↓                                                                true false
                        END IF                                                                                      processing statement B              ELSE-block
                      – Every IF (….) THEN must be balanced by END IF                                 END IF
                        (like parentheses)
               Fortran 90 Lecture 4                   AS 3013                            5    Fortran 90 Lecture 4                     AS 3013                           6




                                                                                              Nesting Structures
               Decision Structures, Control Statements(cont.)
                                                                                              •   The body of any structure, such as an IF-block, may contain another.
                                                                                                        IF (...) THEN            1        'IF' levels
               • For 3 or more branches                                                                    :                     1
               • ELSE IF (…) THEN                                                                       END IF                   1
                                                                                                        :                          0
                          IF (logical expression) THEN              → at start of structure             IF (...) THEN            1
                      Indent …………. IF-block                                                                :                     1
                                                                                                           IF (...) THEN       2
                          ELSE IF (logical expression) THEN        → any number of
            LINE UP




                                                                                                               :               2
                        ……………… ELSE IF-block                          ELSE IFs                             ELSE IF (...) THEN 2
                                                                                                               :               2
                          ELSE                                     → not essential                         ELSE                2
                        ……………… ELSE-block                             but must be last                         :               2
                                                                                                               IF (...) THEN 3
                          END IF                                   → at end of structure                          :          3
                                                                                                               END IF        3
               • The CASE construct                                                                            :               2
                      – The CASE statement (introduced in Fortran 90) provides an                          END IF              2
                        alternative method of selection between a number of branches.                      :                     1
                                                                                                        END IF                   1
                      – See the textbooks for details.
               Fortran 90 Lecture 4                   AS 3013                            7    Fortran 90 Lecture 4                     AS 3013                           8




Lecture 4                                                                                                                                                                          2
Computational Physics - Fortran 90                                                                                                                               25 February 1997




            Nesting Structures (cont.)                                                       Fortran 90              Looping Structures
            • Always make sure the IFs and END IFs balance correctly.                              – Looping structures allow us to repeat blocks of code many times,
                                                                                                     usually with different data values.
            • A structure like IF   IF    END IF is incomplete.
                                                                                             • DO structure
            • Always use INDENTATION to identify blocks at                                         – The only looping construct in Fortran.
              successive nesting levels.                                                           – General form is
                                                                                                        DO loop control
            • Indent each block some consistent number of spaces more
                                                                                                           processing statements
              than the statements delimiting the block.
                                                                                                        END DO
                                                                                                   – The processing statements, forming the loop body or DO-block,
            • The IF statement                                                                       are executed repeatedly as indicated by the loop control.
                  – For when there are no ELSE IF or ELSE conditions and the
                    action when the logical expression is true is a single statement.
                  – IF (logical expression) statement
                  – e.g. IF (X < 0) X = 0
            Fortran 90 Lecture 4                    AS 3013                              9   Fortran 90 Lecture 4                    AS 3013                            10




            Looping Structures (endless)                                                     Looping Structures (endless, cont.)

            • No loop control                                                                      DO
                  DO
                                                                                                        IF (logical expression) EXIT
                       DO-block                                                                              false
                       processing statements                                                            DO-block
                                                                                                        processing statements     true
                  END DO
                  – The statements in the DO-block will be executed repeatedly.                    END DO
                  – This loop will never stop!
                  – Include a logical test and an EXIT statement to terminate it.                  – The EXIT test need not be the first statement in the loop.
                  – EXIT transfers control to the statement following END DO                       – If required, processing statements may precede as well as follow it.



            Fortran 90 Lecture 4                    AS 3013                             11   Fortran 90 Lecture 4                    AS 3013                            12




Lecture 4                                                                                                                                                                      3
Computational Physics - Fortran 90                                                                                                                           25 February 1997




            Looping Structures (endless, cont.)                                          Looping Structures (endless, cont.)

                  e.g.      N = 7                                                        • Include N = N-1 in the loop and it will execute 7 times.
                            DO                                                                    N = 7
                               IF (N <= 0) EXIT                                                   DO
                               PRINT *, N                                                            IF (N <= 0) EXIT
                            END DO                                                                   PRINT *, N
                  – What will happen here?                                                           N = N-1
                  – If there were no output statement such a loop would go on for ever            END DO
                    without it being obvious --- neither compiler nor run-time error     • HINT:
                    checking can detect this error.
                                                                                               Include PRINT *, statements for critical variables at critical points
                                                                                                  while testing.
            • BEWARE OF INFINITE LOOPS                                                         Remove them when you're happy about that section of program.
            • One of the variables in the logical expression must be                           With decision structures you must test your code for correct flow and
              modified in the body of the loop to make it terminate.                              logic.
                                                                                         • If you have a problem add temporary PRINT *, statements.
            Fortran 90 Lecture 4                   AS 3013                          13   Fortran 90 Lecture 4                   AS 3013                             14




            Looping Structures (endless, cont.)                                          Looping Structures (indexed)
            • Endless loops are very useful when you need to read in a                   • Algorithm: loop for index = values do processing statement
              list of numbers and don't know in advance how many there                   •   To execute a processing statement a fixed number of times we could
              will be.                                                                       create an endless loop with a decreasing counter to exit the loop at zero
                                                                                         •   as in the example previously used.
                 e.g. A set of non-negative numbers is followed by a negative one
                              (e.g. 5, 4, 7, 20, 2, -5).                                      N = 7                              Initialize loop counter
                      Find the sum of the non-negative numbers.                               DO
                 Initialize sum to zero. SUM = 0.0                                                 IF (N == 0) EXIT              Test counter
                                                                                                     processing statements         do 7 times
                 Loop                         DO
                                                                                                   N = N-1                       Modify counter
                 Read a number                      READ *, X
                                                                                              END DO
                 If (negative) Exit                 IF (X < 0.) EXIT
                 Add number to sum                  SUM = SUM + X                              – The processing statements may use the counter N
                                              END DO                                           – e.g. to print a table of N**2
            • Layout: INDENT the body of the loop to indicate the structure.                   – Warning: modifying N affects loop control.

            Fortran 90 Lecture 4                   AS 3013                          15   Fortran 90 Lecture 4                   AS 3013                             16




Lecture 4                                                                                                                                                                  4
Computational Physics - Fortran 90                                                                                                                                     25 February 1997




                                   Predetermined Loops                                              Looping Structures (indexed, cont.)
            • The DO statement also provides these facilities and                                           Legally, the loop variable and parameters may be any type, but
              specifies a DO-loop.                                                                            INTEGERs avoid rounding-off problems.
                                                                                                              Non-integer loop variables and parameters will be removed in a
                  DO i = initial_value, final [, increment]                                                   future Fortran standard. So don't use them!
                  e.g. DO i = 7, 0, -1
                  i is the DO variable (loop counter)                                                       DO i = initial value, limit[, increment]
                  Parameters:                                                                    Indent →       processing statements
                      initial_value : the initial value given to i.
                                                                                                            END DO
                                                                                                                                         }    DO-loop
                      final_value : the final value, determines when to stop loop.
                      increment : the value to be added to i each time round (default 1).                   e.g. DO I = 2,10,2 executes loop for I = 2, 4, 6, 8, 10
                                                                                                                 DO I = 2,11,2 also executes loop for I = 2, 4, 6, 8, 10
                  OBLIGATORY: i is an INTEGER variable.                                                                        because next time would be 12, > limit 11
                    the parameters are INTEGER variables, constants or expressions.                              DO I = 1,5    executes loop for I = 1, 2, 3, 4, 5
                                                                                                            but DO I = 5,1,-1 executes loop for I = 5, 4, 3, 2, 1
                                                                                                    • Don't change loop index yourself within loop.
            Fortran 90 Lecture 4                      AS 3013                               17      Fortran 90 Lecture 4                     AS 3013                           18




            Looping Structures (indexed, cont.)                                                     Looping Structures (cont.)
            • To use real numbers work as follows:                                                  • Nesting
                  e.g. to tabulate 2sinx + 3.165x2 e x from 0 to 3.5 in steps of 0.01                     DO loops of both kinds may be nested as any block may contain
                  INTEGER :: I                                                                              another complete structure.
                  REAL :: X, Y                                                                            DO I = 1,N
                  DO I = 0, 350                                                                             DO J = 1,M
                       X = REAL(I)/100.0                                                                                           inner loop     outer loop
                       Y = 2.0*SIN(X) + 3.165*X*X*EXP(X)                                                    END DO
                       PRINT *, Y                                                                         END DO
                  END DO                                                                                  DO loops may be included in IF-blocks and vice-versa.
            • While loops:                                                                                But a structure must be wholly contained within a block of another
                                                                                                            structure.
                  – These may be constructed using endless DO loops with the test
                    and EXIT statement.                                                             • Use EXIT to get out of a loop if you need to.
                                                                                                    • Also see CYCLE statement in text books.
            Fortran 90 Lecture 4                      AS 3013                               19      Fortran 90 Lecture 4                     AS 3013                           20




Lecture 4                                                                                                                                                                            5