Docsity

Notes on Fortran Procedures: Subprograms and Functions | MSC 321, Study notes of Earth Sciences

Toggle sidebar
bg1
Chapter 5
Fortran Procedures: Subprograms
and Functions
Numerical programming often requires repeating the same calculations with differ-
ent data and variables. Examples include having to integrate different functions or
the same function over different intervals repeatedly. Having to recode the same
chunk of fortran statement is wasteful of time and error prone as typos and bugs
can be introduced in the process, moreover, the time we have invested in validating
a specific piece of code would have to be duplicated again and again. Most pro-
gramming languages provide a mechanism to avoid these repetitions and pitfalls.
In FORTRAN this is done simply and elegantly by turning algorithmically related
code segments into subprograms or procedures. There are many kinds of sub-
programs in FORTRAN: subroutines,functions, and BLOCK DATA subprograms.
Moreover, subroutines and functions can come in two flavors, internal and exter-
nal. The func function already encountered in the trapezoidal rule integration is
one example of an internal procedure. Subprograms are essential to build complex
software as it allows programmers to think of their code in terms of algorithmic
units and permits some degree of code abstraction. The benefits is that the de-
velopment and validation of code can be done flexibly and in manageable units.
Validated software can also be reused without having to worry repeatedly about
its correctness.
5.1 Modular Design
The example of trapezoidal integration will be used again to illustrate the use of
external procedures; the code for an adaptive trapezoidal integration is listed in
??. Clearly one can see a division of tasks among the different portions of the code.
More specifically, one can distinguish the following phases in the program:
•An initialization phase that primarily reads in the input data; lines 8-9.
33
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Notes on Fortran Procedures: Subprograms and Functions | MSC 321 and more Study notes Earth Sciences in PDF only on Docsity!

Chapter 5

Fortran Procedures: Subprograms

and Functions

Numerical programming often requires repeating the same calculations with differ- ent data and variables. Examples include having to integrate different functions or the same function over different intervals repeatedly. Having to recode the same chunk of fortran statement is wasteful of time and error prone as typos and bugs can be introduced in the process, moreover, the time we have invested in validating a specific piece of code would have to be duplicated again and again. Most pro- gramming languages provide a mechanism to avoid these repetitions and pitfalls. In FORTRAN this is done simply and elegantly by turning algorithmically related code segments into subprograms or procedures. There are many kinds of sub- programs in FORTRAN: subroutines, functions, and BLOCK DATA subprograms. Moreover, subroutines and functions can come in two flavors, internal and exter- nal. The func function already encountered in the trapezoidal rule integration is one example of an internal procedure. Subprograms are essential to build complex software as it allows programmers to think of their code in terms of algorithmic units and permits some degree of code abstraction. The benefits is that the de- velopment and validation of code can be done flexibly and in manageable units. Validated software can also be reused without having to worry repeatedly about its correctness.

5.1 Modular Design

The example of trapezoidal integration will be used again to illustrate the use of external procedures; the code for an adaptive trapezoidal integration is listed in ??. Clearly one can see a division of tasks among the different portions of the code. More specifically, one can distinguish the following phases in the program:

  • An initialization phase that primarily reads in the input data; lines 8-9.

34 CHAPTER 5. FORTRAN PROCEDURES: SUBPROGRAMS AND FUNCTIONS

1 program trap 2 implicit none 3 integer :: N! number of intervals 4 real :: a,b! interval extrema 5 integer :: maxiteration! maximum number of iterations allowed 6 integer :: i, iteration! counters 7 real :: dx, Ans, xi, error, Ansold, tolerance

8 print ,’Enter a, b,tolerance, initial N, maxiteration’ 9 read , a,b, tolerance, N, maxiteration 10 do iteration = 1,maxiteration! iteration count 11 dx = (b-a)/real(N)! grid size 12 Ans = 0.5( myfunc(a) + myfunc(b) )! Evaluate function at a and b 13 do i = 1,N- 14 xi = idx + a 15 Ans = Ans + myfunc(xi) 16 enddo 17 Ans = Ans * dx! Integral estimate with N points 18 if (iteration > 1) then! one iteration before check 19 error = abs(Ans - Ansold) 20 if (error < tolerance) then! absolute error 21 exit! converged, exit loop 22 else! if not converged do following 23 N = 2*N! double number of intervals 24 Ansold = Ans! store old answer 25 endif 26 else 27 error = 0. 28 endif 29 print *, N, Ans, error 30 enddo 31 print *, N, Ans, error! print final answer

32 stop 33 contains 34 real function myfunc(x) 35 implicit none 36 real, intent(in) :: x 37 myfunc = x** 38 return 39 end function myfunc 40 end program trap

Figure 5.1: Code for adaptive trapezoidal integration

36 CHAPTER 5. FORTRAN PROCEDURES: SUBPROGRAMS AND FUNCTIONS

1 program trap 2 implicit none 3 integer :: N! number of intervals 4 real :: a,b! interval extrema 5 integer :: maxiteration! maximum number of iterations allowed 6 integer :: i, iteration! counters 7 real :: dx, Ans, xi, error, Ansold, tolerance 8 9 print *,’Enter a, b,tolerance, initial N, maxiteration’ 10 read , a,b, tolerance, N, maxiteration 11 Ansold = Trapezoid(a,b,N)! first estimate of integral 12 do iteration = 2,maxiteration! iteration count 13 N = 2N! double number of intervals 14 Ans = Trapezoid(a,b,N)! new estimate of integral 15 error = abs(Ans - Ansold)! absolute error 16 if (error < tolerance) then 17 exit! converged, exit loop 18 else 19 Ansold = Ans! save old answer if not converged 20 endif 21 print *, N, Ans, error! monitor adaptation progress 22 enddo 23 print , N, Ans, error! print final answer 24 25 stop 26 contains 27 28!*********************************************************************** 29! Numerical integration via trapezoidal rule 30!*********************************************************************** 31 real function Trapezoid(a,b,N) 32 implicit none 33 integer, intent(in) :: N 34 real, intent(in) :: a,b 35 integer :: i 36 real :: x,dx, res 37 dx = (b-a)/real(N) 38 res = 0.5 * (myfunc(a)+myfunc(b)) 39 do i = 1,N- 40 x = idx + a 41 res = res + myfunc(x) 42 enddo 43 Trapezoid = dx * res 44 return 45 end function Trapezoid

5.2. FUNCTIONS AND SUBROUTINES 37

program numinteg implicit none integer :: N,maxiteration real :: a,b,ainteg, tolerance call Input(a,b,tolerance,N,maxiteration) call AdaptTrapezoid(ainteg,a,b,tolerlance,N,maxiteration) print ,’Integral = ’, ainteg stop contains! the functions Trapezoid and myfunc should go below here !*********************************************************************** ! Adaptive integration !*********************************************************************** subroutine AdaptTrapezoid(ainteg,a,b,tolerance,N,maxiteration) implicit none integer, intent(inout) :: N, maxiteration real, intent(in) :: a,b, tolerance real, intent(out) :: ainteg integer :: iteration real :: Ans, Ansold,err Ansold = Trapezoid(a,b,N)! first estimate of integral do iteration = 2,maxiteration! iteration count N = 2N! double number of intervals Ans = Trapezoid(a,b,N)! new estimate of integral error = abs(Ans - Ansold)! absolute error if (error < tolerance) then exit! converged, exit loop else Ansold = Ans! save old answer if not converged endif print *, N, Ans, error! monitor adaptation progress enddo return end subroutine AdaptTrapezoid end program numinteg !*********************************************************************** ! Input parameters !*********************************************************************** subroutine Input(a,b,tolerance,N,maxiteration) implicit none integer, intent(out) :: N, maxiteration! number of subinterval real, intent(out) :: a,b, tolerance! interval print *,’Enter a, b,tolerance, initial N, maxiteration’ read *, a,b, tolerance, N, maxiteration return end subroutine Input

5.3. CALL BY REFERENCE 39

and will not be changed by the routine, these are given the intent(in) at- tribute. Others have no value upon entry to the subroutine, but their value is assigned upon exist; they are given the intent(out) attribute. Finally some arguments, have a value upon entry that is modified in the course of the subroutine execution, these are given the intent(inout) attribute. The intent attribute is not part of classical FORTRAN, but is extremely useful in documenting the code by immediately telling the programmer what vari- ables are modified. Furthermore, declaring the attribute allows the compiler to first check and alert the programmer if a value is changed inadvertantly, and second to perform some optimization.

  • The variables x and i are local to subroutine Trapezoid and they have nothing to do with variables having the same name in other routines, includ- ing the calling routine. The scope of these variables is local to subroutine Trapezoid.
  • Local variables are not necessarily saved across subroutine invocation even though some compiler do so by default. If we want to insure that local vari- ables keep their values across, we would use the attribute save in declaring the variable.
  • The main program and the subroutines it calls are each compiled separetely, one at a time. This separate compilation is the reason that the names of variables in dummy argument lists and local variables, having nothing to do with the names of variables in other routines. The compiler in translating each routine into machine language has no way of knowing about any other routines to be used in the program. Only the loader knows about all the pieces that must be linked together to create the executable; by that time all variable names would have been translated into memory addresses. Separate compilation is one of the great features of FORTRAN as it allows the building and use of libraries.
  • Subprograms can invoke other subprograms to any depth. The only exception is that subprogram can invoke themselves in classical FORTRAN. Recursion is actually a new feature added to FORTRAN 90.

5.3 Call by reference

How are arguments transferred from the invoking subroutine to the called sub- routine? One could imagine that a subroutine copies actual arguments into its dummy arguments at invocation, performs the calculations, and then the output arguments are copied back after the return. That would actually be a waste of memory and CPU, both precious commodities in the early days of computing.

40 CHAPTER 5. FORTRAN PROCEDURES: SUBPROGRAMS AND FUNCTIONS

FORTRAN uses instead what is known as call by reference or call by name because what is passed to the subroutine is not the value of the actual argument but its memory address. Subprograms manipulates the actual parameters directly by addressing the memory location where they are stored. Address calculation takes place entirely behind the scenes and memory locations are not directly avail- able to the FORTRAN programmer. So if a subrprogram changes the value of a dummy argument, the value of the actual argument gets changed immediately. For this reason, passing arguments that have the same name can lead to surprising results if their values are changed and can be potentially dangerous. This is called aliasing of arguments.

5.4 Function Subprograms

Function subprograms are very similar to subprograms but there are some impor- tant differences.

  • Functions return a single variable in the name of the function itself, no sep- arate variable need be devoted to the return value.
  • A subroutine does not have a type (and does not need to have one). But a function’s name returns a value and hence must have a type. The compiler knows about its built-in functions like sqrt but it has to be told the type of user defined functions.
  • There are specific functions for every variable type, dsqrt for example returns a double precision variable. Fortran, however, allows some functions to have generic names, and the function invoked depends on the data type of the input argument. For example sqrt(4.0) returns a 32-bit real result whereas sqrt(4.d0) returns a 64-bit real since 4.d0 is a double precision constant.
  • A subroutine is invoked with call whereas a function is invoked simply by mentioning its name in an expression.
  • A subroutine is allowed to not have any parameters, but classical FORTRAN insists that a function must have at least one parameter.
  • The scope of a function are delimited by the function and end function statements.
  • The function’s name must be assigned a result and the compiler should com- plain if it is not.
  • Functions and subroutines can invoke other functions. Special considerations should be taken to handle recursive functions.

42 CHAPTER 5. FORTRAN PROCEDURES: SUBPROGRAMS AND FUNCTIONS

module trapez contains !*********************************************************************** ! Adaptive integration !*********************************************************************** subroutine AdaptTrapezoid(ainteg,a,b,tolerance,N,maxiteration) implicit none integer, intent(inout) :: N, maxiteration real, intent(in) :: a,b, tolerance real, intent(out) :: ainteg integer :: iteration real :: Ans, Ansold,err Ansold = Trapezoid(a,b,N)! first estimate of integral do iteration = 2,maxiteration! iteration count N = 2*N! double number of intervals Ans = Trapezoid(a,b,N)! new estimate of integral error = abs(Ans - Ansold)! absolute error if (error < tolerance) then exit! converged, exit loop else Ansold = Ans! save old answer if not converged endif print , N, Ans, error! monitor adaptation progress enddo return end subroutine AdaptTrapezoid !*********************************************************************** ! Numerical integration via trapezoidal rule !*********************************************************************** real function Trapezoid(a,b,N) implicit none integer, intent(in) :: N real, intent(in) :: a,b integer :: i real :: x,dx, res dx = (b-a)/real(N) res = 0.5 * (myfunc(a)+myfunc(b)) do i = 1,N- x = idx + a res = res + myfunc(x) enddo Trapezoid = dx * res return end function Trapezoid end module trapez

5.6. RECURSIVE PROCEDURES 43

program numinteg use trapez implicit none integer :: N,maxiteration real :: a,b,ainteg, tolerance call Input(a,b,tolerance,N,maxiteration) call AdaptTrapezoid(ainteg,a,b,tolerlance,N,maxiteration) print *,’Integral = ’, ainteg stop contains! the functions Trapezoid and myfunc should go below here . . .

Figure 5.5: Usage of a module .

??, the corresponding code that uses the module is shown in ??. Notice that the main program has the statement use trapez to instruct the compiler to associate the subroutine AdaptTrapezoid with the one declared within the module. The module can be in a separate file or within the same file as the main program. In either cases, the use requires that the module trapez be compiled prior to the main program. Hence if it is included in the file containing the main program, it must precede it. The compiler can hence process and produce the information that the module need provide the main program with.

5.6 Recursive Procedures

Fortran by default does not permit functions of subroutines to call themselves either directly or indirectly. However, complex algorithms can often be cast elegantly in terms of recursive calls, that is the algorithm divides the steps into subtasks that are identical by require different data. In that sense recursive procedures resemble do-loops by are much more powerful. They are also more expensive as a procedure call, and as local variable must be created for each instance the procedure is called. Let us revisit the example of trapezoidal integration. Our adaptive procedure doubled the number of points uniformely, regardless of the shape of the function. This can be wasteful in places where the function behaves mostly like a straight line since the trapezoidal error is already small there. The error analysis reveals that the errors are largest in regions where the curvature of the function is large. A more astute adaptation strategy would resolve the high curvature regions, only sparse sampling of the function would be necessary in regions where it behaves

5.6. RECURSIVE PROCEDURES 45

! Numerical integration via trapezoidal rule !*********************************************************************** recursive real function TrapezoidRec(a,b,tolerance) implicit none real, intent(in) :: a,b,tolerance real :: xm,dx, est1, est2, error, myfunc dx = (b-a)! interval width xm = 0.5(a+b)! interval midpoint est1 = 0.5 * (myfunc(a)+myfunc(b)) * dx! one-trapeze estimate est2 = 0.5 * (dx * myfunc(xm) + est1)! two-trapeze estimate error = abs(est2 - est1) if (error > 3.0tolerance) then est1 = TrapezoidRec(a,xm,0.5*tolerance) print , xm est2 = TrapezoidRec(xm,b,0.5tolerance) TrapezoidRec = est1 + est else TrapezoidRec = est endif return end function TrapezoidRec

Figure 5.6: Recursive trapezoidal integration

Cell numbers

x

Figure 5.7: Quadrature points for the recursive trapezoidal rule, the grid spacing for these boxes is shown in the right hand figure.